You need to use Member Initialization List
B(int v):a(v) { }
FROM
B(int v) { a = A(v);
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.
source share