Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 498
Saif Avatar asked Oct 13 '16 19:10

Saif


3 Answers

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.

like image 173
Galik Avatar answered Oct 05 '22 22:10

Galik


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.

like image 40
Brian Bi Avatar answered Oct 05 '22 23:10

Brian Bi


You may cheat with private inheritance

class B : private A
{
public:
    using A::f1;
    using A::f2;
};
like image 33
Jarod42 Avatar answered Oct 05 '22 22:10

Jarod42