Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to base class validity

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);
like image 915
jmasterx Avatar asked Oct 06 '10 20:10

jmasterx


2 Answers

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.

like image 79
GManNickG Avatar answered Oct 09 '22 13:10

GManNickG


Both are valid - a child can be used in a place where a reference/pointer to parent is expected. This is called polymorphism.

like image 28
Karel Petranek Avatar answered Oct 09 '22 11:10

Karel Petranek