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 cas
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.
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.
Your question is not clear becuse it mixes up several different things.
On the one hand, a pointer to derived class can be converted to a pointer to a base class (assuming the base is accessible). This is a natural conversion and there's no need for any cast to do it.
On the other hand, you mention dynamic_cast
and its ability to to perform downcasts. But downcasts are casts in the opposite direction: from a pointer to a base class to a pointer to derived class. Downcasts can be performed by both dynamic_cast
and static_cast
depending on what you need and what amount of run-time checking you require.
... And at the same time you ar talking about casting the result of new
, which, of course, can only be upcasted, but not downcasted.
So, what is it you are asking about? Upcasts or downcasts?
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;