Riz
Riz

Reputation: 51

Can a superclass inherit methods from its sub class?

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

Answers (2)

Mark Ransom
Mark Ransom

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

sampson-chen
sampson-chen

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

Related Questions