Inheriting both an interface and a C ++ implementation

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

So, here is what I want to do ... I want to define a base interface and a derived interface. Then I want to implement a basic interface with additional variables and methods. Finally, I want to implement the Derived class from an implemented base interface, BUT ALSO from a derived interface. I donโ€™t know about you, but my head hurts.

If I do something like the following, I get Undefined definitions in the DerivedFloat code, because this code โ€œseesโ€ the GetBaseValue method from IBase inherited from IDerivedFloat, as well as GetBaseValue inherited from Base.

Of course, there must be a way to get a class that uses the advanced features of the base implementation, and also make sure that it implements the required IDerivedFloat methods.

Now ... This is a dummy example to show what I'm conceptually trying to achieve. This is 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 };
}
0
source share
2 answers

You can use virtual inheritance to solve 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, you get one instance of a class of base classes, and not one of them every time it exists in the class hierarchy.

+3
source

- , , . , , super .

:
- C A B.
- A B add().
- C A:: add() B:: add(), , .

: http://www.cprogramming.com/tutorial/multiple_inheritance.html

0

All Articles