简体   繁体   中英

C++ Cannot use getter function inherited from base class

The only way I can access Vehicle::color from within Sedan class, is by reimplementing the getter method. I want to access it from the subclass, without doing so.

// Base Class
class Vehicle
{
protected:
    bool windowIsOpen[4];
    int  wheels;
    char *color;

public:
Vehicle(char *color) : color(color){};
char *getColor() { return color; }
};

class Sedan : Vehicle
{
public:
    Sedan(char* color) : Vehicle(color) {}
};

int main(int argc, char **argv){
    Sedan se("green");
    cout<<se.getColor()<<endl;
    return 0;
}

When defining your class, you wrote class Sedan : Vehicle . This is effectively the same as class Sedan : private Vehicle . In other words, Vehicle is an implementation detail that ain't exposed to users of Sedan. To make this public inheritance, you should write class Sedan : public Vehicle .

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