Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to a ptr to ptr of derived class [duplicate]

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;
}
like image 884
Itay Avraham Avatar asked Aug 17 '16 13:08

Itay Avraham


1 Answers

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

like image 163
Wyzard Avatar answered Sep 29 '22 06:09

Wyzard