0

I am having a hard time trying to understand why the variable engineNum is inaccessible from within the function in the class Pickup. My basic understanding is, if the class is inherited the private variables should be accessible. This isn't the case I am finding:

class Truck
{
private:
    string model;
    Truck() {};
    static int TruckEngineNum;
    int engineNum;
public:
    Truck(const string& model) 
    {
        this->model = model;
        engineNum = TruckEngineNum++;
    };

    string getModel() 
    {
        return model;
    }
    int getEngineNum() 
    {
        return engineNum;
    }
};
int Truck::TruckEngineNum = 100;

class Pickup : public Truck
{
public:
    Pickup(const string& model) : Truck(model) 
    {
        if((engineNum % 2) == 1){ engineNum++; };
    }
};
Switchkick
  • 2,716
  • 6
  • 21
  • 28

1 Answers1

4

private variables are not accessible by derived classes. If you want to have access to it, you'll need to declare it as protected.

Also, your Truck class should declare a virutal destructor if you plan to use it as a polymorphic base class.

Yuushi
  • 25,132
  • 7
  • 63
  • 81
  • Believe it or not, that was my first thought, and I did change the code to reflect that. Is it bad practise to use (in any case) protected rather than private? – Switchkick Jun 13 '13 at 01:24
  • It depends. The rule of thumb is make everything private unless you absolutely can't. If you definitely need access to that variable in a derived class, then make it protected - just realize that it will couple the classes together more, hence certain modifications to the base class will be more difficult to make. – Yuushi Jun 13 '13 at 01:25
  • 3
    Usually you want member variables private in all cases, even when you need access in derived classes. If you make sure to have, say, a public getter and a protected setter, that allows derived classes to modify the data, but still allows the base class to enforce guarantees about its internal state. If you make data members protected, then your derived classes can do whatever they want with them, even if it breaks the base class behavior. – Cogwheel Jun 13 '13 at 01:27