5

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;
}
Peter K
  • 1,372
  • 8
  • 24
Itay Avraham
  • 125
  • 6

3 Answers3

8

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

Wyzard
  • 33,849
  • 3
  • 67
  • 87
  • My program working well when I use SomeFunction((Base**)&c). Which problem may appear at run time? @Wyzard – Itay Avraham Aug 17 '16 at 14:14
  • 1
    Right, there's just no *implicit* cast. Your explicit cast overrides the compiler's type-checking — just like you can cast a `Child1*` to a `Child2*` even though they're unrelated types. Casting `Child**` to `Base**` should be OK as long as you only assign pointers to compatible types (i.e. don't do what I did in the example). – Wyzard Aug 17 '16 at 14:17
1

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

Because Child** is not implicitly convertible to Base**.

Can I use pointer to pointer when I deal with derived class?

If by that you mean "Can I assign Child** to a variable of Base** type", then the answer is: No, you can not.

eerorika
  • 232,697
  • 12
  • 197
  • 326
1

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

If the compiler did allow you automatic conversion of pointer-to-pointers, you would get the following bad example (adapted from https://stackoverflow.com/a/2532428/2079934) running:

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

c now points to a Base, not to a Child.

Community
  • 1
  • 1
SpamBot
  • 1,438
  • 11
  • 28
  • *"Child\* is not a derived class of Base\*"* is vacuously true since pointers aren't class types at all :) – StoryTeller - Unslander Monica Aug 17 '16 at 14:04
  • 3
    Since the Q&A you link to is a perfect target for this thread to be marked as dupe to, consider next time when you know of such dupe target thread to propose a (possible) dupe target rather than needlessy duplicating the dupe target's information in the dupe. – dfrib Aug 17 '16 at 14:05