Reputation: 415
I have class A and B. B is a member of A. I need to initialize B with other data members of A.
class A;
class B
{
public:
B(A& a){cout << "B constr is run \n";}
};
class A
{
public:
A(){}
void initB(A& a){b(a); cout << "A call init B \n"; }
private:
// other members ...
B b;
};
int main()
{
A a;
a.initB(a);
}
I got compile error:
classIns.cpp: In constructor âA::A()â:
classIns.cpp:14: error: no matching function for call to âB::B()â
classIns.cpp:8: note: candidates are: B::B(A&)
classIns.cpp:6: note: B::B(const B&)
classIns.cpp: In member function âvoid A::initB(A&)â:
classIns.cpp:16: error: no match for call to â(B) (A&)â
Why A(){} needs to call B::B() ?
How to initialize B with other data members of A ?
thanks
Upvotes: 0
Views: 168
Reputation: 64283
Like this :
void initB(A& a){
b = B(a);
cout << "A call init B \n";
}
Off course, the class B needs a default constructor, and a copy constructor that takes reference to the object of type A.
Upvotes: 1
Reputation: 129984
B
has no default constructor, which means you have to initialise it in A
's ctor.
struct A {
A() : b(*this) {}
private:
B b;
};
Any time you think of using init
-like members, you're probably doing it wrong. Object should always be valid after the constructor is done.
Upvotes: 4
Reputation: 3099
You can use initialization chain in A constructor:
class B
{
public:
B(Type1 x, Type2 y)
{
}
void init(Type1 x, Type2 y) { ........}
};
class A
{
public:
A() : Amember1(), Amember2(), b(Amember1, Amember2) {}
private:
Type1 Amember1;
.....
B b;
};
But you can't invoke B constructor inside initB
method because b is already constructed.
You can use a B::init()
method with A data, like:
void A::initB(A& a){ b.init(a.Amember1, a.Amember2); cout << "A call init B \n"; }
Upvotes: 1
Reputation: 26940
Why A(){} needs to call B::B() ?
Because A has a data member B which needs to be initialized when you create an instance of the A class. In your case b is initialized with the default B c'tor.
Since you are specifying a constructor for B
public:
B(A& a){cout << "B constr is run \n";}
The default constructor :
B(){}
is not automatically generated by the compiler. So it complains.
Upvotes: 0