简体   繁体   中英

c++ Delete inherited member variable in child class

Consider the following code:

Struct Base 
{
   int x;
   double y;    
}

Struct A : public Base
{   
}

Struct B : public Base
{  //here I don't want x (Base::x) to be inherited.
   // is there a way to delete it (something like delete Base::x)
}

Struct C : public Base
{   
}

What is considered best practice to achieve such a task? x should be inherited by A and C , (and maybe by many other classes) so I can't put it in the private section of Base . The only way I see is to remove x from Base and put it in A & C . But there should be another way right? Thanks.

There is no way to "delete" inherited data members, and you cannot even hide them. They get intrinsic part of the subclass. If B shall inherit just parts of Base , you need to split Base :

Struct Base 
{
   double y;    
}

Struct BaseWithX : public Base
{
   int x;
}

Struct A : public BaseWithX
{ }

Struct B : public Base
{ }

Struct C : public BaseWithX
{ }

Public inheritance makes an is-a relationship. That means B is a Base . And that means if Base has x then since B is a Base , B will have x . You need to re-think this design if you have that problem. Consider switching the relationship between B and Base to composition:

struct B {
    void some_function_using_base();
private:
    Base base_;
};

In terms of hiding a member of the base class, you can achieve that by inheriting privately from it and selectively exposing public (or protected) base class members using using :

Struct Base 
{
   int x;
   double y;    
}

Struct A : public Base
{   
}

Struct B : private Base
{  
   using Base::x; // only pull in x in the public section of the class
}

...

B b;
double y = b.y // <= compilation error here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM