Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Array Constructor

I was just wondering, whether an array member of a class could be created immediately upon class construction:

class C
{
      public:
          C(int a) : i(a) {}

      private:
          int i;
};

class D
{
 public:
        D() : a(5, 8) {}
        D(int m, int n) : a(m,n) {}

     private:
     C a[2];

};

As far as I have googled, array creation within Constructor such as above is in C++ impossible. Alternatively, the array member can be initialized within the Constructor block as follows.

class D
    {
     public:
         D() { 
               a[0] = 5;
               a[1] = 8; 
             }
         D(int m, int n) { 
                           a[0] = m;
                           a[1] = n; 
                         }
         private:
         C a[2];

    };

But then, It is not an array creation anymore, but array assignment. The array elemnts are created automatically by compiler via their default constructor and subsequently they are manually assigned to specific values within the C'tor block. What is annoying; for such a workaround, the class C has to offer a default Constructor.

Has anybody any idea which can help me in creating array members upon construction. I know that using std::vector might be a solution but, due to project conditions I am not allowed to use any standard, Boost or third party library.

like image 697
Necip Avatar asked Dec 22 '09 06:12

Necip


1 Answers

Arrays -- a concept older than C++ itself, inherited straight from C -- don't really have usable constructors, as you're basically noticing. There are few workaround that are left to you given the weird constraints you're mentioning (no standard library?!?!?) -- you could have a be a pointer to C rather than an array of C, allocate raw memory to it, then initialize each member with "placement new" (that works around the issue of C not having a default constructor, at least).

like image 140
Alex Martelli Avatar answered Sep 22 '22 00:09

Alex Martelli