C++ Cannot use getter function inherited from base class

Viewed 1662

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;
}
1 Answers

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.

Related