Casting from ptr to ptr of a derived class

Why am I getting a compilation error if I don't specify an explicit cast in Base **?

Can I use a pointer to a pointer when working 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; } 
+5
source share
3 answers

Although you can implicitly drop Child* into Base* , there is no implicit translation from Child** to Base** because it can be used to violate type security. 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 info in the C ++ FAQ

+8
source

Why did I get a compilation error if I don’t list the listing on Base** ?

Because Child** implicitly converted to Base** .

Can I use a pointer to a pointer when working with a derived class?

If by this you mean "Can I assign Child** variable of type Base** ", then the answer will be: No, you cannot.

+1
source

Child is a derived class of Base , but Child* not a derived class of Base* .

If the compiler allowed you to automatically convert pointers to pointers, you will get the following incorrect example (adapted from fooobar.com/questions/434366 / ... ):

 Child *c = new Child; Base **bb = &c; *bb = new Base; 

c now points to a Base , not Child .

+1
source

All Articles