c++classpointersinheritancebase-class

base class pointing to inherited class


I have an inherited class which i would like to point to from the base class. Example below

class Base
{
    inherited* test;
};

class inherited: Base
{
};

the purpose of this is so that the base class (a character) contains a linked list of the inherited class (items)

ps apologies for any mistakes, i'm new to this site


Solution

  • It might be possible to trick the compiler into accomplishing this, but it's most certainly bad OOP design. If all you want to do is be able to store an instance of the inherited class but can treat it like the base class, then you can simply make inherited* test a base* test and it will accept pointers to either inherited or base (or any other subclass of base).

    If you actually want base to treat that instance as inherited, you need to rethink your class hierarchy because you don't actually have an inheritance tree here.