How to implement a Delphi array type property

Sep 9, 2011 at 1:13pm
Hi,

I'm trying to convert some code from C++ Builder to standard C++. The code heavily rely's on Delphi's TList and uses the Propery Items.

I've come up with the way of writing a TList class with a child class inside. Using an operator overload on [] in the child class i've managed to simulate the property in standard C++.

The code to achieve this is below:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Header

   class TList
   {
   public:
      int    Size;
      int    Count;
      void **ItemsData;

      class TListItem
      {
      public:
         TList *Owner;

         TListItem()
         {
            Owner = NULL;
         }

          void *operator [](const int idx) const
          {
             if (Owner)
                return(Owner->GetItem(idx));

             return(NULL);
          }

      } Items;


      TList();
      ~TList();

      void Allocate(int NewCount);

      void* GetItem(const int idx);

      int Add(void *Item);
   };


   // Implementation


   TList::TList()
   {
      Size  = 0;
      Count = 0;
      Data  = NULL;

      Items.Owner = this;
   }

   TList::~TList()
   {
      free(Data);
   }

   void TList::Allocate(int NewSize)
   {
      Data =(void **)realloc(Data,sizeof(void *)*NewSize);

      if (NewSize>Size)
         memset(&Data[Size],0,sizeof(void *)*(NewSize-Size));

      Size = NewSize;
   }

   int TList::Add(void *Item)
   {
      if (Count>=Size)
         Allocate(Size + 16);

      if (Data)
         Data[Count++] = Item;
   }

   void* TList::GetItem(const int idx)
   {
      return(Data[idx]);
   }


Then using my TestList() function I have successfully proven that the code works:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
   void TestList()
   {
      TList *pList = new TList();

      pList->Add((void *)100);
      pList->Add((void *)200);
      pList->Add((void *)300);

      int Value = (int)pList->Items[0];

      pList->Add((void *)Value);

      delete(pList);
   }



My question is is there a simpler way of implementing this ability without having a class within a class?

Thanks

Simon
Last edited on Sep 9, 2011 at 1:15pm
Sep 9, 2011 at 11:07pm
you could use list or vector :)
vector<type> variable;

1
2
3
4
5
6
7
8
9
10
11
12
#include <vector>

vector<int> vector;

vector.push_back(100);
vector.push_back(200);

cout<<vector[0]; //100
cout<<vector[1]; //200

vector[0] = 500;
Topic archived. No new replies allowed.