Create a class that contains all but one of the functions of its parent class

Suppose I have two classes, one of them:

class A{ public: void f1() { cout << "function 1"; } void f2() { cout << "function 2"; } void f3() { cout << "function 3"; } }; 

Now I want class B contain all the functions of A except f3 .

What am I doing:

 class B: public A { private: void f3() { } }; 

To my knowledge, B::f3() hides the definition of A::f3() , and since B::f3() is private, f3() not accessible through class B But I can still do it like this:

 B var(); var.A::f3(); 

Is it possible to completely hide f3 from class B using inheritance and without changing class A ?

+5
source share
3 answers

Don't use the habit of putting classes together through inheritance, mixing and matching classes that do just about what you want. This leads to terrible code.

However, sometimes it makes sense to implement one class using another. In these cases, if you use inheritance, the โ€œrightโ€ way to do this is to use private inheritance.

And by โ€œright,โ€ I mean the most acceptable way.

 class A { public: void f1() { cout << "function 1"; } void f2() { cout << "function 2"; } void f3() { cout << "function 3"; } }; class B: private A { public: using A::A; // use A constructors using A::f1; using A::f2; // do not use f3 }; 

The time when this may make sense is when the composition is too tedious due to the number of methods used.

+9
source

You must not make B inherit from A

If B lacks some of the functions of A , then B and A do not have an is-a relationship, which inheritance is for modeling (and what clients will expect). Instead, you should use composition: type member B type A

+9
source

You can cheat on a private inheritance

 class B : private A { public: using A::f1; using A::f2; }; 
+4
source

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


All Articles