Why do I get a compilation error if I don't specify an explicit cast to Base** ?
Can I use a pointer to pointer when I deal with a derived class?
class Base { };
class Child : public Base { };
void SomeFunction(Base** ppoObj) {}
void SomeFunction(Base* poObj) {}
int main()
{
Child *c = new Child();
// This passed.
SomeFunction(c);
SomeFunction((Base**)&c);
// CompilationError
SomeFunction(&c);
return 0;
}
Although you can implicitly cast Child*
to Base*
, there's no implicit cast from Child**
to Base**
, because it could be used to violate type-safety. Consider:
class Base { };
class Child1 : public Base { };
class Child2 : public Base { };
int main() {
Child1 *c = new Child1();
Base **cp = &c; // If this were allowed...
*cp = new Child2(); // ...then this could happen. (*cp is a Base*)
}
More information in the C++ FAQ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With