Ojmeny
Ojmeny

Reputation: 1426

How to initialize object in different class?

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?

Upvotes: 3

Views: 113

Answers (2)

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20759

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

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

You can do it the following way

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

Upvotes: 2

Related Questions