Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a pointer of a derived class be type cast to the pointer of its base class?

Tags:

c++

The pointer of derived class returned by new can be type cast to the pointer of its base class.

Is this true or false?

I know dynamic_cast can be used to cast downside. Generally, how to cast a pointer of derived class to a pointer of its base class?

like image 397
skydoor Avatar asked Jan 28 '10 16:01

skydoor


3 Answers

Yes. Conversion from a pointer to a derived class to a pointer to a base class is implicit. Thus, the following is perfectly fine:

struct B { };
struct D : B { };

D* my_d_ptr = new D;
B* my_d_ptr_as_a_b_ptr = my_d_ptr;
like image 182
James McNellis Avatar answered Oct 13 '22 17:10

James McNellis


Casting a pointer to a derived to a pointer to base should be implicit. This is the whole point of polymorphism: An instance of a derived class should always be safely usable as an instance of the base class. Therefore, no explicit cast is necessary.

like image 22
dsimcha Avatar answered Oct 13 '22 17:10

dsimcha


That's true if derived class inherits 'publicly' and 'non-virtually' from base:

You can't convert Derived* to Base* neither implicitly nor using static_cast/dynamic_cast (C-cast will do the job, but you should think twice before use this hack!);

class Base { };

class Derived : protected Base { };

int main()
{
   Base* b = new Derived(); // compile error
}

Also don't work if base class is ambiguous:

class Base { };

class Derived1 : public Base { };
class Derived2 : public Base { };

class MostDerived : public Derived1, Derived2 { };

int main()
{
   Base* b = new MostDerived(); // won't work (but you could hint compiler
                                // which path to use for finding Base
}

Edit: added code samples, added ambiguous use case, removed virtual inheritance example.

like image 40
Alexander Poluektov Avatar answered Oct 13 '22 18:10

Alexander Poluektov