Why is the Child class’s converter constructor called in the code below?
I mean, it automatically converts Base to Child via the Child converter constructor. The code below compiles, but shouldn’t it not compile since I haven’t provided bool Child::operator!=(Base const&)?
class Base
{
};
class Child : public Base
{
public:
Child() {}
Child(Base const& base_) :
Base(base_)
{
std::cout <<"should never called!";
}
bool operator!=(Child const&)
{
return true;
}
};
void main()
{
Base base;
Child child;
if(child != base)
std::cout << "not equal";
else
std::cout << "equal";
}
Because you provided a conversion constructor. If you don’t want the compiler to automatically convert
Baseobjects toChildusing theconstructor, make it explicit:
This way, the constructor will only be called when you explicitly specify it, in contexts like: