Search code examples
c++classinheritancemodifiers

Variable inaccessible?


In the code below the variable 'id' is inaccessible in the class Horse, is this an inheritance issue? An access modifiers issue? Any help is greatly appreciated.

class Animal
{
private:
   int id;
};

class Horse : public Animal
{
public:
   Horse(){
      if((id % 2) == 1) { id++ };
   } 
};

Solution

  • class Horse only inherits public and protected elements in this case if you use:

    class Horse : public Animal
    

    to inherit id, you can define this private element in Animal class as protected:

    class Animal
    {
    protected:
      int id;
    };