Can a constructor call another class constructor in C ++?

class A { public: A(int v) { _val = v; } private: int _val; }; class B { public: B(int v) { a = A(v); // i think this is the key point } private: A a; }; int main() { B b(10); return 0; } 

the compiler says:

 test.cpp: In constructor 'B::B(int)': test.cpp:15: error: no matching function for call to 'A::A()' test.cpp:5: note: candidates are: A::A(int) test.cpp:3: note: A::A(const A&) 

I have studied Java and I do not know how to handle this in C ++. Look for a couple of days, plz tell me, can C ++ do this?

+4
source share
3 answers

You need to use Member Initialization List

 B(int v):a(v) { } 

FROM

 B(int v) { a = A(v); // i think this is the key point } 

a value is assigned , not initialized (this is what you intend). As soon as the body of the constructor begins { , all its members are already built.

Why are you getting an error message?
The compiler builds a before the start of the constructor body { , the compiler uses the no constructor of argument a because you did not tell it otherwise Note 1 since there is no default argument constructor, therefore, there is no error.

Why is the default argument constructor not implicitly generated?
Once you create any constructor for your class, an implicitly created argument constructor is no longer generated. You have provided overloads for constructor a and, therefore, there is no implicit constructor generation without arguments.

Note 1
Using the Member initializer list is a way to tell the compiler to use a specific overloaded version of the constructor, rather than the default argument constructor.

+15
source

You need to use initialization lists:

 class B { public: B(int v) : a(v) { // here } private: A a; }; 

Otherwise, the compiler will try to build A using the default constructor. Since you do not provide it, you get an error message.

+6
source

Yes, it is possible, but you did not provide a default constructor for A (one that accepts no parameters or all parameters have default values), so you can only initialize it in the initializer list:

 B(int v) : a(v) { } 

This is because before the constructor body enters, A will be built (or try to build) using the default constructor (which is not available).

+2
source

Source: https://habr.com/ru/post/1414705/


All Articles