Sam
Sam

Reputation: 151

Use 'new' in constructor? c++

Say I have two classes, myclass1 and myclass2. And suppose myclass2 has a field myclass1 object1. So the myclass2 header looks something like this:

 class myclass2 {
      public:
             myclass2();
             myclass2(int arg);
      private:
             myclass1 object1;
}

And suppose myclass1 has a header like this:

 class myclass1 {
      public:
             myclass1();
             myclass1(int arg);
      private:
             int var1;
}

Now suppose in my main function I want to instantiate an object of type myclass2, like so:

int main(){

         myclass2 object2(int VAR);

}

Then in order for object2's private field object1 to have private field var1 set equal to VAR upon instantiation of object2, should the constructor for myclass2 be like this(?):

myclass2::myclass2(int arg){
         object1 = object1(arg);

}

Or would this work(?):

   myclass2::myclass2(int arg){
         object1(arg);

}

Or in this situation must I have a mutator function in myclass1 to access object1's private field var1 in the constructor for myclass2?

Finally, would this do the job(?):

 myclass2::myclass2(int arg){
         myclass1 *type1pointer;
         type1pointer = new myclass1(arg);
         object1 = *type1pointer; 

}

Upvotes: 1

Views: 924

Answers (1)

Jarod42
Jarod42

Reputation: 217275

Use initializer list:

class myclass2 {
public:
    myclass2(int arg) : object1(arg) {}
private:
    myclass1 object1;
};

Thus you initialize your object only once. This way, object1 default constructor isn't called, thus avoiding default-constucting and then a specific myclass1 mutator

Upvotes: 6

Related Questions