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
?
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.
You should not make B
inherit from A
.
If B
lacks some functionality of A
, then B
and A
do not have the is-a relationship that inheritance is intended to model (and which clients will expect). You should use composition instead: introduce a member of B
of type A
.
You may cheat with private inheritance
class B : private A
{
public:
using A::f1;
using A::f2;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With