Itay Avraham Itay Avraham - 8 months ago 51
C++ Question

Casting to a ptr to ptr of derived class

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.

// CompilationError

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