Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a way in c++ to hide a specific function

i have an inheritance struct A : public B, i want to hide individual functions from B, is this possible?

i know the opposite is possible using using BMethod in the A declaration.

cheers

like image 583
lurscher Avatar asked Feb 05 '11 17:02

lurscher


4 Answers

If you want to selectively hide functions from B it does not make much sense to use public inheritance in the first place.
Use private inheritance & selectively bring methods from B into the scope of A:

struct B{
   void method1(){};
   void method2(){};
};
struct A : private B{
   using B::method1;
};

A a;
a.method1();
a.method2(); //error method2 is not accesible
like image 197
Eugen Constantin Dinca Avatar answered Oct 17 '22 09:10

Eugen Constantin Dinca


There is an issue here: this would be a direct violation of the Liskov Substitution Principle, namely A would not act as a B any longer.

If you wish to reuse B implementation, the solution is simply to do so:

class A
{
public:
  void foo() { return b.foo(); }
  void bar() { return b.bar(); }
  // ...

private:
  B b;
};

Don't abuse inheritance, use composition instead

like image 31
Matthieu M. Avatar answered Oct 17 '22 07:10

Matthieu M.


The using keyword can be used to change visibility

struct A
{
    void method1();
};

struct B: public A
{
    void method2();

    private:
    using A::method1;
};
like image 26
xaviersjs Avatar answered Oct 17 '22 09:10

xaviersjs


Aside from the ways described in the previous answers—composition, private inheritance, and non-private inheritance but with the inherited method declared private—another way is to explicitly delete the inherited method:

#include <iostream>

struct A {
    void foo() { std::cout << "foo\n"; }
};

struct B : A {
    void foo() = delete;
};

int main() {
    B b;
    b.foo(); // COMPILER ERROR
}

Although the b.foo() call produces a compiler error, client code can still call the base class’s version by qualifying with the base class identifier A:

b.A::foo(); // compiles, outputs 'foo' to console

This explicit deletion way works when foo is not a virtual non-deleted method in A. By C++11 Standard §10.3/16, this explicit deletion is ill-formed when the deleted method in the derived class overrides a virtual non-deleted method of the base class. For more info on this restriction, see the answers to the SO question C++11 Delete Overriden Method.

like image 16
CodeBricks Avatar answered Oct 17 '22 07:10

CodeBricks