Itay Avraham Itay Avraham - 3 months ago 7
C++ Question

Casting ptr to ptr of derived class

Why I got an compilation error if I don't specify a casting to Base** ?

Can I use pointer to pointer when I deal with 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;
}

Answer

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