lambda
lambda

Reputation: 1235

C++ Object Construction inside a Class

I have three classes; their function definitions are in a sperate file. I'm trying to construct an object with various parameters inside another class without using inline implementation.

class A{     
     public:
       A(){}  
};

class B{         
     public:
         //takes in two ints, one reference to object, and a string 
         B(int x, int y, A &a, std::string s );
};

class C{        
    public:            
        //in the constructor, construct b_obj with its parameters 
        C();

    private:
        B b_obj;
 };

How can I make the C constructor construct b_obj with its parameters of the int, the reference to an instance of A, and the string? I tried some methods but I get an error that complains about no match call to the b_obj constructor.

Upvotes: 1

Views: 203

Answers (2)

John3136
John3136

Reputation: 29266

You need to pass the relevant items to a constructor of object C, and then use an initializer.

class C {
    public:
        C(int x, int y, A& a, std::string s) : b_obj(x, y, a, s) {}

Upvotes: 1

Qaz
Qaz

Reputation: 61970

Use an initializer:

C() : b_obj(5, 6, A(), ""){}

This line technically won't work, though, because B's constructor takes an A&, so you can't bind a temporary to it. const A & if it's not being changed, or A if it is, would work out better if you don't have a non-temporary A to pass in.

Upvotes: 2

Related Questions