Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize object in different class?

Tags:

c++

I'm learning c++ and I have problem with basics. How to init object in different class?

For example I have code:

class A {

  private:
     static int num;
     static string val;

  public:
    A(int n, string w) {        
       num = n;
       val = w;
   }
};

I want to create object A in class B, so I have try like this:

class B {
   private:
      A objA;
   public:
      B(int numA, string valA){
         objA = new A(numA, valA);
   }
};

Different ways(same constructor):

 public:
      B(A obA){
        objA = obA;
      }

or

 public:
      B(int numA, string valA){
         objA = A(numA, valA);
      }

Always I'm getting error: No default constructor for exist for class "A". I've read that default constructor is constructor without any arguments, but I give them, so why it is searching default?

like image 779
Ojmeny Avatar asked Jun 24 '26 11:06

Ojmeny


2 Answers

If you want to learn C++ ... forget java. C++ variables are values, not pointers in reference disguise.

objA = new something is an abomination, since objA is A and not A*.

What you need is just explicitly construct objA with proper parameter

class B {
   private:
      A objA;
   public:
      B(int numA, string valA) 
          :objA(numA, valA) 
      {
      }
   }
};

For more reference see http://en.cppreference.com/w/cpp/language/initializer_list

like image 56
Emilio Garavaglia Avatar answered Jun 26 '26 02:06

Emilio Garavaglia


You can do it the following way

class B {
   private:
      A objA;
   public:
      B(int numA, string valA) : objA( numA, valA ) {}
};
like image 31
Vlad from Moscow Avatar answered Jun 26 '26 00:06

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!