Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not inherit a variable in C++ classes

With C++ classes, you can have a derived class inherit a variable from its parent class. How can I define the derived class so that var2 is not inherited in derivclass?

class mainclass{
public:
    int var1;
    char var2;
    void test(){
        cout<<var1<<var2<<endl;
    }
}
class derivclass : mainclass{
public:
    void test(){
        cout<<var1<<var2<<endl;
        //want a compiler error here that var2 is not defined
    }
}
like image 475
tomsmeding Avatar asked Apr 17 '13 18:04

tomsmeding


1 Answers

You can make it private. But you probably shouldn't.

The fact that it shouldn't inherit some stuff from Base means it probably shouldn't inherit from Base directly at all.

Instead create another base class and make the two classes inherit from that base.

class Baseclass{
public:
    void test(){
        cout<<var1<<endl;
    }
protected:
    int var1;

}

class mainclass : public Baseclass{
public:
    char var2;
    void test(){
        cout<<var1<<var2<<endl;
    }
}

class derivclass : Baseclass{
public:
    void test(){
        cout<<var1<<endl;
    }
}
like image 165
stardust Avatar answered Oct 01 '22 22:10

stardust