Consider following class
class test { public: test(int x){ cout<< 'test \n'; } };
Now I want to create array of 50 objects of class test . I cannot change class test.
Objects can be created on heap or stack.
Creating objs on stack is not possible in this case since we dont have default constructor in class
test objs(1)[50]; /// Error...
Now we may think of creating objs on heap like this..
test ** objs = NULL; objs = (test **) malloc( 50 * sizeof (test *)); for (int i =0; i<50 ; ++ i) { objs[i] = new test(1); }
I dont want to use malloc .Is there any other way??
If you guys can think of some more solutions , please post them…
You cannot create an array of objects, as in Foo foo [N], without a default constructor. It’s part of the language spec.
Either do:
You don’t need malloc(). You can just declare an array of pointers.
But you probably ought to have some sort of automatic RAII-type destruction attached.
OR subclass test publicly:
and then:
You can treat every TempTest object as a test object.
Note: operator=() & copy constructor are not inherited, so respecify as necessary.