Dynamic array of objects in a class.

I have an assignment wherein i have to make a dynamic array of objects, which has to be made in another class. This leads me to write something like this in the constructor of ClassA:

ClassA::ClassA(int myMax, string paramB)
{
myArray = new ClassB[myMax];
...
}

It gives an error there because for some reason, it assumes i want to call the constructor of ClassB. Is there any way i can fix this?

(ps: I'm aware i could use vectors and save myself the frustration, but i'm being forced to use dynamic arrays. This is one of many reasons i hate the damn things.)
It gives an error there because for some reason, it assumes i want to call the constructor of ClassB.


It assumes this because you have to call the constructor for ClassB. Failure to call a ctor results in an incompete object, which is potentially dangerous. (Look how badly your ClassA class would screw up if the ctor wasn't called -- if you tried to use an array that you never allocated. That kind of thing is what C++ is protecting you from).

The only thing you need to do to fix this is give ClassB a default ctor. If you don't need the ctor to do anything, just have it empty.
It gives an error there because for some reason, it assumes i want to call the constructor of ClassB. Is there any way i can fix this?

It is right. You want to call a constructor ^^.

No, really. Allocating an array of objects call the default constructor for every object in the array. If you don't have a default constructor (but have any other constructor, whiich prevents the auto-generation of a default constructor) then you can't use this class directly in an array.

You can have an array of pointers to the object.

Ciao, Imi.
PS: Damn. Disch beat me. ;)
Last edited on
Ok, i made some adjustments and i got most of the errors out, but now i'm faced with another one. When i try to add a new object to this dynamic array i made, it gives this strange operator error.

I initialise a new object, and attempt to add it like this, with "i" being a place in the array where i know for a fact nothing has been added before (that i know of):

ClassB objectName = new ClassB();
myArray[ i ] = objectName;

I've also tried initialising it directly to the array, omitting the objectName, and it gives the same error.
I'm going crazy here, messing with dynamic arrays has already tripled the time i usually spend on this kind of programs.
Topic archived. No new replies allowed.