Dynamic allocation of multiple objects within class

Mar 23, 2012 at 12:28am
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

Thanks!
Last edited on Mar 23, 2012 at 12:30am
Mar 23, 2012 at 1:11am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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.

Mar 23, 2012 at 1:29am
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 ;)
Topic archived. No new replies allowed.