Conversion of pointer-to-pointer between derived and base classes?
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:
- Why is there no implicit conversion from Child** to Base**?
- 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 usestatic_cast
instead?
Solution 1:
If this was allowed, you could write this:
*bb = new Base;
And c
would end up pointing to an instance of Base
. Bad.
Solution 2:
Pointers are virtual address. Normally you are responsible for what you do with it. Using msvc 2019. I can cast one to base, but not two:
example 1:
int p;
int *p1 = &p;
int **p2 = &p1; //OK
example 2:
struct xx {};
struct yy : public xx {};
yy p;
yy *p1 = &p;
xx **p2 = &p1; //Just a strange error
example 3:
struct xx {};
struct yy : public xx {};
yy p;
xx *p1 = &p;
xx **p2 = &p1; //OK