Blue-unicorne
Blue-unicorne

Reputation: 377

Inheriting from both an interface and an implementation C++

I usually try to find answers here before I post anything, but I'm not even sure how to formulate my question.

So here's what I want to do... I want to define a Base Interface, and a Derived Interface. Then, I want to implement the Base Interface, with extra variables and methods. Finally, I want to implemented a Derived class, from the implemented Base Interface BUT ALSO from the Derived Interface. I don't know about you, but my head hurts.

If I do something like below, I get Ambiguous definitions under the DerivedFloat code since that code "sees" both the GetBaseValue method from the IBase, inherited through IDerivedFloat, as well as the GetBaseValue inherited from Base.

Surely, there must be a way to derive a class which uses the expanded features of the Base Implementation, as well as making sure it implements the required IDerivedFloat methods.

Now... This is a dummy example to show what I'm conceptually trying to achieve. It's not a real life example.

template <typename VALUE_TYPE>
class IBase
{
public:
  virtual VALUE_TYPE GetBaseValue() const = 0;
};

class IDerivedFloat : public IBase<FLOAT>
{
public:
  virtual void SetBaseValue(const FLOAT & value) = 0;
};

// Implementation of Base
template <typename VALUE_TYPE>
class Base : public IBase<VALUE_TYPE>
{
public:
  VALUE_TYPE GetBaseValue() const { return m_BaseValue; }

protected:
  VALUE_TYPE m_BaseValue;
}

// Uses expanded Base AND implements IDerivedFloat
class DerivedFloat : public Base<FLOAT>, public IDerivedFloat
{
public:
   void SetBaseValue(const FLOAT & value) { m_BaseValue = value };
}

Upvotes: 0

Views: 192

Answers (2)

Andy
Andy

Reputation: 30418

You can use virtual inheritance to work around this problem:

class IDerivedFloat : virtual IBase<FLOAT>
{
public:
  virtual void SetBaseValue(const FLOAT & value) = 0;
};

template <typename VALUE_TYPE>
class Base : virtual IBase<VALUE_TYPE>
{
public:
  VALUE_TYPE GetBaseValue() const { return m_BaseValue; }

protected:
  VALUE_TYPE m_BaseValue;
}

Using virtual inheritance gives the derive class one instance of the base class members, instead of one from each time it exists in the class hierarchy.

Upvotes: 3

Kadima
Kadima

Reputation: 249

Multiple inheritance is an issue precisely because of the ambiguity issue you ran into, but there are ways to get around it. You have to explicitly tell the compiler which super you are calling the ambiguous functions from, by leading the function call with the super's name and a double colon.

Example:
- C inherits from A and B.
- A and B both have add() function.
- In C, you have to say A::add() or B::add() to tell the compiler which one to use.

Link for details and more complete implementation: http://www.cprogramming.com/tutorial/multiple_inheritance.html

Upvotes: 0

Related Questions