Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why must C++ constructor use dynamic allocation for array?

In my course notes these two examples are given. Apparently the first one is not allowed, is there a technical reason why I can't allocate on stack? Or is this the C++ standard?

   // Constructor may force dynamic allocation when initializating an array of objects.

   Complex ac[10];             // complex array initialized to 0.0
    for ( int i = 0; i < 10; i += 1 ) {
         ac[i] = (Complex){ i, 2.0 } // disallowed
    }


    // MUST USE DYNAMIC ALLOCATION
    Complex *ap[10];            // array of complex pointers
    for ( int i = 0; i < 10; i += 1 ) {
         ap[i] = new Complex( i, 2.0 ); // allowed
    }
like image 584
Mark Avatar asked Jan 24 '26 07:01

Mark


1 Answers

The first one is not valid syntax. But assuming your Complex class has a public copy-assignment operator (the implicit one should probably be fine), then the following should be fine:

Complex ac[10];             // complex array initialized to 0.0
for ( int i = 0; i < 10; i += 1 ) {
     ac[i] = Complex( i, 2.0 );
}
like image 161
Oliver Charlesworth Avatar answered Jan 26 '26 22:01

Oliver Charlesworth