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;
}
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’ve learned Java, and I don’t know how to deal with this in C++.
Searching for a couple days, plz tell me can C++ do this?
You need to use a Member Initialization List
With:
ais being assigned a value and not being initialized(which is what you intend), Once the body of an constructor begins{, all its members are already constructed.Why do you get an error?
The compiler constructs
abefore constructor body{begins, the compiler uses the no argument constructor ofAbecause you didn’t tell it otherwiseNote 1, Since the default no argument constructor is not available hence the error.Why is the default no argument constructor not generated implicitly?
Once you provide any constructor for your class, the implicitly generated no argument constructor is not generated anymore. You provided overloads for constructor of
Aand hence there is no implicit generation of the no argument constructor.Note 1
Using Member Initializer List is the way to tell the compiler to use particular overloaded version of the constructor and not the default no argument constructor.