if we compiled the following code, the compile would complain "no matching function for call to 'fruit::fruit()' "
i think the reason is : apple constructor call a default fruit constructor and it can't find one
but if I removed apple constructor(commented out from LineA to LineB) and compiled again. it is compiled without error. why? from book, if we didn't define any constructor for apple class. the compiler will create one. why the apple default constructor created by compiler doesn't complain about missing fruit::fruit() . thanks
class fruit
{
public:
int seed;
//fruit()
//{
// cout <<"fruit" <<endl;
// seed = 12;
//}
fruit(int i)
{
cout <<i<<"fruit"<<endl;
}
virtual void plant()
{
cout << "fruit" <<endl;
}
};
class apple:public fruit
{
public:
apple() //lineA
{
//cout << "apple" << endl;
} //lineB
void plant()
{
cout << "apple" << endl;
}
};
int main(){}
thanks
I know how to make this code work. my question is why removing the apple default constructor doesnt cause compilation error.
[ C++11 standard.]
12.1.5. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4).
12..1 ..."The implementation will implicitly define them if they are odr-used"...
So, if you remove apple::apple()
, the implementation may not create apple::apple()
unless it is actually called, and hence has no need to reference fruit::fruit()
.
As given, the code does not call apple::apple()
.