views:

85

answers:

1

Regarding the following C++ program:

class Base { };

class Child : public Base { };

int main()
{   
    // Normal: using child as base is allowed
    Child *c = new Child();
    Base *b = c;

    // Double pointers: apparently can't use Child** as Base**
    Child **cc = &c;
    Base **bb = cc;

    return 0;
}

GCC produces the following error on the last assignment statement:

error: invalid conversion from ‘Child**’ to ‘Base**’

My question is in two parts:

  1. Why is there no implicit conversion from Child** to Base**?
  2. I can make this example work with a C-style cast or a reinterpret_cast. Using these casts means throwing away all type safety. Is there anything I can add to the class definitions to make these pointers cast implicitly, or at least phrase the conversion in a way that allows me to use static_cast instead?
+8  A: 

If this was allowed, you could write this:

*bb = new Base;

And c would end up pointing to an instance of Base. Bad.

Marcelo Cantos
Small correction - he could say `**bb = new Base();` Just `*bb` wouldn't be allowed.
Phil
@Phil: `new` returns a pointer, which is type `*Base`. `bb` is of type `**Base`. Thus `*bb` is the right level of dereference.
Amber
The rationale is essentially the same as the comp.lan.g.c FAQ about the non-equivalence of `char**` and `char const**`: http://c-faq.com/ansi/constmismatch.html
Michael Burr
@Dav: sorry, I was assuming you replaced the line `Base **bb = cc`, with `Base **bb = new Base()`. Don't know where I got that idea though, since if I thought that, your `Base *b = new Base()` would be perfectly legal. My mistake!
Phil