K
K
Kirill Margorin2015-03-11 11:49:33
OOP
Kirill Margorin, 2015-03-11 11:49:33

How to implement inheritance from the interfaces branch and the base implementation of the root interface?

Let's assume that there is a certain set of public interfaces (exported by the library):

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

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

And there is also a basic implementation of the IA interface:
class A : public IA {
public:
  void f1() {
    std::cout << "f1" << std::endl;
  }
};

It is necessary to implement the IB interface so that it provides an implementation of the IA interface by class A:
// Этот код не компилируется
class B :  public IB, public A
{
public:
  void f2() {
    std::cout << "f2" << std::endl;
  }
};

int main(int argc, char* argv[])
{
  B b;
  b.f1();
  b.f2();
  return 0;
}

Code on Coliru
Is it possible to do this, and how?
The solution "on the forehead" did not fit, with the order and visibility (public/protected/private) of inheritance was played ... nothing helped.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill Margorin, 2015-03-11
@comargo

I found the answer to the question
https://isocpp.org/wiki/faq/multiple-inheritance#m...
I learned that not only functions are virtual, but also inheritance.
Thank you.
Final code:

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

class IB : virtual public IA { // !!! VIRTUAL !!!
public:
  virtual void f2() = 0;
};

class A : virtual public IA { // !!! VIRTUAL !!!
public:
  void f1() {
    std::cout << "f1" << std::endl;
  }
};

class B :  public IB, public A // А вот тут виртуальность необязательна.
{
public:
  void f2() {
    std::cout << "f2" << std::endl;
  }
};

int main(int argc, char* argv[])
{
  B b;
  b.f1();
  b.f2();
  return 0;
}

J
jcmvbkbc, 2015-03-11
@jcmvbkbc

Why not just

class B :  public IB, A
{
public:
        void f1() {
                A::f1();
        }
        void f2() {
                std::cout << "f2" << std::endl;
        }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question