Saif Ullah Saif Ullah - 1 month ago 8
C++ Question

Create a class that contains all functions of its parent class except one

Suppose I have two classes,
one is:

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


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

what I am doing is:

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

}
};


According to my knowledge,
B::f3()
is hiding the definition of
A::f3()
, and as
B::f3()
is private,
f3()
is not accessible via class
B
. But what I can still do is call it like this:

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


Is there any way I could completely hide
f3
from class
B
using inheritance and without changing class
A
?

Answer

Don't get in the habit of piecing classes together through inheritance by mixing and matching classes that do roughly what you want. That leads to awful code.

However, occasionally it does make sense to implement one class by means of another. In those cases, if you are using inheritance, the "correct" way to do it is by using private inheritance.

And by "correct" 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's constructors
    using A::f1;
    using A::f2;
    // do not use f3
};

The times when this may make sense is when composition is way too tedious because of the number of methods involved.

Comments