Multiple Inheritance: Using a Private Base Member Function

Here is my problem:

#include <iostream> using namespace std; class A { public: virtual void f() = 0; }; class B { public: void f() {cout << "Hello world!" << endl;}; }; class C : public A, private B { public: using B::f; // I want to use B::f as my implementation of A::f }; int main() { C c; // error: C is abstract because f is pure virtual cf(); } 

So far I have found two workarounds:

  • Define a function f in class C that just calls B :: f. But this is tedious and not so clean (especially when you do this for a bunch of functions)

  • B inherits from A and C inherits from B (all public). For me, this is not consistent with the design. In particular, B is not A, and I do not want B to depend on A.

Can you imagine any other possibility?

+4
source share
1 answer

The declaration of use adds the function B::f to the scope of the class for searching, but the function is still B::f , not C::f . You can define the implementation in a derived type and move on to the implementation of B::f , otherwise you will have to change the inheritance hierarchy so that both B and C inherit (in fact) from A

 void C::f() { B::f(); } // simple forwarding implementation 
+3
source

Source: https://habr.com/ru/post/1500974/


All Articles