Reputation: 51
I know that subclasses can inherit methods from the super class, but can a super class do the same for its sub class? For example:
Alpha *a = new Alpha ();
Beta *b = new Beta ();
Gamma *g = new Gamma ();
g = b;
On the fourth statement, I am creating a Gamma object to be a Beta object, but Gamma is the super class and beta is the sub class. So either g gets a pointer to b or this code will not compile and I do not quite understand which answer is correct. If someone could please clarify that would be great.
Upvotes: 2
Views: 411
Reputation: 308130
It can't inherit them technically, but it can use them if you use the Curiously Recurring Template Pattern (CRTP).
template<class SubClass>
class SuperClass
{
void DoSomething()
{
static_cast<SubClass *>(this)->Foo();
}
};
class SubClass: public SuperClass<SubClass>
{
void Foo();
};
Upvotes: 2
Reputation: 47267
No, superclass cannot inherit methods from its subclass because in general a superclass should not have any knowledge of what derive from it.
Upvotes: 1