Can someone give me a most simple example of dynamic allocation of say n objects within a parent class?
Lets say there is a constructor of the parent that is passed n, we set the child pointer with new
child = new Child[n];
and in the parent private we have Child child*;
Something along these lines, I am having some unusual segmentation fault errors and just need a simple example to follow. Also, I need a method from the parent that calls the constructor of one of the objects (elements) from the child, like
child[i].init();
just to see if this is how it is called, or does it need to be via a pointer or something
class Child {
public:
//default constructor says hi
Child() { cout<<"Child Constructor"; }
//destructor says wazzup
~Child() { cout<<"Child Destrucotr"; }
};
class Parent {
int numberOfChilds;
Child* myChild;
public:
Parent( int n ): myChild(NULL) , numberOfChilds(n) {
//create n childs from the argument
myChild = new Child[n];
if ( !child ) { //not enough space do what you have to do }
//constructor says hi
cout<<"Parent Constructor";
}
~Parent() {
//delete every obejct made by new
//check if it is null even though its safe to delete a null pointer
if ( child ) delete [] myChild;
cout<<"Parent Destructor";
}
};
everything you want to initiate in child you can do it in the constructor and it will be called by the compiler every time you create a new object like the new operator does. myChild = new Child[n];
with this line you 'll have a new space in memory with n Childs and myChild pointing at the first child of that space.
You will see that the Childs construcotr anounces itself with the new operator.
At the destructor you delete what myChild points to. delete [] myChild;
If you forget the brackets then the only thing you deleting is the first child.So with the brackets you say to the compiler to delete the whole array of Childs.
new will never return 0. If it can't allocate the memory it throws an exception, which, if not caught, will terminate your program. So, checking for new returning 0 is useless ;)