Interface implementations and multiple inheritance in C++

| category: Programming | author: st
Tags:

Multiple inheritance of interfaces which are pure abstract classes indeed is not a problem until you need to use the interface implementation in other classes.

Suppose there are two interfaces, the implementation of which will be used in other classes.

class IA
{
public:
    virtual void m1() = 0;
};

class IB : public IA
{
public:
    virtual void m2() = 0;
};

// Common IA implementation
class A : public IA
{
public:
    virtual void m1() { cout << "A::m1" << endl; }
};

// B implement both IA and IB but would use IA implemenation of A
class B : public IB, public A
{
public:
    virtual void m2() { cout << "B::m2" << endl; }
};

This code will not compile because the conflict between IA::m1() and B::m1() cannot be resolved. A simple "head-on" solution is to override the function but you will need to add some useless code.

class B : public IB, public A
{
public:
    virtual void m1() { A::m1(); }
    virtual void m2() { cout << "B::m2" << endl; }
};

A more elegant solution is to use the virtual inheritance. In this case, the class B inherits only a copy of the functions IA (contains only one instance of IA) and ambiguity is resolved.

class IA
{
public:
    virtual void m1() = 0;
};

class IB : public virtual IA
{
public:
    virtual void m2() = 0;
};

// Common IA implementation
class A : public virtual IA
{
public:
    virtual void m1() { cout << "A::m1" << endl; }
};

// B implement both IA and IB but use IA implemenation of A
class B : public IB, public A
{
public:
    virtual void m2() { cout << "B::m2" << endl; }
};