I get the message:
Severity Code Description Project File Line Suppression State Error (active) E0339 class "D" has more than one default constructor)
and:
Severity Code Description Project File Line Suppression State Error C2668 'D::D': ambiguous call to overloaded function)
The error occurs in line marked with //(2)
if I remove line marked with //(1) the I can build my code.
class C {
int i, j;
public:
C(int x, int y) : i(x), j(y)
{
cout << "Konstr C" << endl;
}
C() : i(0), j(0)
{
cout << "Std-Konstr C" << endl;
}
~C()
{
cout << "Destruktor C" << endl;
}
};
class D : public C {
int k, a, b;
C c;
public:
D():c(){ cout << "Std-Konstr D" << endl; }// (1)
D(int x = 1) :c(x, 1), a(x), b(0), k(19)
{
cout << "Konstr-1 D" << endl;
}
D(int x, int y, int z) :C(x, y), a(1), b(2), c(x, y), k(z)
{
cout << "Konstr-2 D" << endl;
}
~D()
{
cout << "Destruktor D" << endl;
}
};
class E : public D {
int m;
C c;
D b;
public:
E(int x, int y) : c(2, 3), b(y), m(x + y)// (2)
{
cout << "Konstr E" << endl;
}
~E()
{
cout << "Destruktor E" << endl;
}
};
As the error message states, D()
is ambiguous. The compiler has no way pf knowing if you meant to call the no-arg constructor, or the int
constructor with a default value of 1
.
One way to clear this ambiguity is to remove the default value of the x
parameter:
D():c(){ cout << "Std-Konstr D" << endl; }// (1)
D(int x) :c(x, 1), a(x), b(0), k(19)
// ^-- x=1 was removed here
{
cout << "Konstr-1 D" << endl;
}