user5182786
user5182786

Reputation:

Inherit from arbitrary class in c++?

Is it possible to design a class that will inherit from any one of a group of base classes? I would like to be able to write something like:

class Derived : public ArbitraryBase {
    public:
        Derived () : ArbitraryBase () {}

    ...
};

where ArbitraryBase can be some base class determined at compile time. I have a group of base classes that I would like to derive identical classes from. Is there a way to avoid writing an individual derived class for each of the base classes?

Upvotes: 1

Views: 199

Answers (2)

lvella
lvella

Reputation: 13443

If it is truly determined at compile time, you can make your derived class a template:

template<class T>
class Derived : public T {
    public:
        Derived() {}

    ...
};

You can later create instantiate this class by providing the base type:

int main() {
    Derived< ??? > my_object;

    ...
}

Where ??? is some compile time way of getting your derived type.

Upvotes: 8

NathanOliver
NathanOliver

Reputation: 180630

You can do this via a template. Using

template<typename T>
class Derived : public T
{
public:
    Derived() : T() {}
    // or just use if actually need to provide a default constructor
    Derived() = default;
};

gives you a class that inherits from T and calls T's default constructor. You would create a concrete class with it like

Derived<Base1> d;

and now d is a Derived that inherits from Base1.

If you need to inherit from an arbitrary number of bases then you can use a variadic template like

template<typename... Bases>
class Derived : public Bases...
{
public:
    Dervied() : Bases()... {}
    // or just use if actually need to provide a default constructor
    Derived() = default;
};

and it would be used like

Derived<Base1, Base2, ..., BaseN> d;

Upvotes: 4

Related Questions