Say I have a class named Base
and a class that derives from it called SuperBase
. Given that add
takes in a Base*
, would either of these be valid:
SuperBase *super = new SuperBase;
bases.add(super);
Or
SuperBase *super = new SuperBase;
bases.add((Base*)super);
The first works as long as SuperBase
publicly derives from Base
, via an implicit conversion from derived-to-base:
struct base { virtual ~base() {} };
struct derived : base {};
base* b = new derived; // okay
The second works as well, but ignores the protection of Base
:
struct derived : private base {}; // private base
base* b = new derived; // not okay, base is private
base* b = (base*)(new derived); // okay, but gross
If it's private
, you probably shouldn't cast to it.
Both are valid - a child can be used in a place where a reference/pointer to parent is expected. This is called polymorphism.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With