freeze
freeze

Reputation: 75

Multiple inheritance: accessing common interface

Given the following:

class A {
//
}

class B {
//
}

class Ad1 : public A {
//
}

class Ad2 : public A {
//
}

class Ad1B : public Ad1, public B {
//
}

class Ad2B : public Ad2, public B {
//
}

Types Ad1B and Ad2B share a common inherited interface (the combined interface of A and B). Is it possible to create a pointer to which objects of either type Ad1B or Ad2B can be assigned, and through which this shared interface can be accessed? Is there any way to achieve the same effect?

Upvotes: 0

Views: 63

Answers (2)

Guillaume Racicot
Guillaume Racicot

Reputation: 41820

You want a pointer to a base class that doesn't exist. You want some pointer to a type that have a combined interface of A and B. You must create a new type that have that interface.

You may pick three approaches : the template approach or the, the interface approach, or the adapter approach.


template

The template approach is quite easy. Your function that need that combined interface simply receive a reference to a T and user your object. If T have that combined interface, it will compile. It will even work with public data members.


interface

The interface approach will need to make changes to your classes. You may create that interface like this :

struct AB {
    // Add virtual member function
    // That is the combined version of A and B
};

Now Ad1B and Ad2B must inherit from the AB interface.


adapter

The adapter is a mix of the template and the interface. You must have an interface AB just as above, but instead of making Ad1B and Ad2B implement it, you create a templated adapter :

template<typename T>
struct Adapter : AB {
    T& object;

    // Override foo from AB
    void foo() override {
        object.foo();
    }
};

You can then use the AB interface in your code. Where you'd use the combined interface.

Upvotes: 0

j2ko
j2ko

Reputation: 2539

The common interface of Ad1B and Ad2B is A and B - so you could store pointer to object of class Ad1B or Ad2B either in A*p or in B*p and access A or B functionality respectively

Upvotes: 1

Related Questions