B
B
borzykot2017-07-24 18:52:20
OOP
borzykot, 2017-07-24 18:52:20

C++: how to inherit simultaneously from the base class and the "interface" while both of them have a common "interface"?

Glossary: ​​An interface is a class with purely virtual stateless functions.
Let's say there is some basic interface. Other interfaces are inherited from it. From them - the working classes. More or less like this:

struct block_i
{
  virtual ~block_i() = default;
  virtual bool is_done() const = 0;
  //...
};
template<class T>
struct consumer_block_i : public block_i
{
  virtual void register_producer(producer_block_i<T>&) = 0;
  //...
};
template<class T>
struct action_block : public consumer_block_i<T>
{
  virtual bool is_done() const override { return false; }
  virtual void register_producer(producer_block_i<T>&) override {}
  //...
};

There are several classes like action_block, and they all contain some of the same code. I would like to put it in a base class, let's say block_base, inherit it from block_i. to get something like this:
struct block_base : public block_i
{
  virtual bool is_done() const override { return false; }
};

template<class T>
class action_block 
  : public virtual block_base
  , public virtual consumer_block_i<T>
{
  virtual void register_producer(producer_block_i<T>&) override {}
  //...
};

But I can't do this in C++ (well, or I don't know how) - I get a compilation error. In C# you can do this:
interface IBlock
{
  bool IsDone();
}

interface IConsumer : IBlock
{
  void RegisterProducer(IProducer producer);
}

class BlockBase : IBlock
{
  public bool IsDone() { return false; }
}

class Consumer : BlockBase, IConsumer
{
  private IProducer producer_;

  public void RegisterProducer(IProducer producer) { producer_ = producer; }
}

Question: how to implement the same in C++? If it's possible of course. I do not want to put some default implementations in interfaces.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Fat Lorrie, 2017-07-24
@Free_ze

virtual inheritance

D
devalone, 2017-07-24
@devalone

google virtual inheritance.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question