Pregunta

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++ };
   } 
};
¿Fue útil?

Solución

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

Otros consejos

You probably want id to be protected and not private, then. Or better, use the accessor you wrote...

id is private to Animal and therefore inaccessible to Horse. A satisfactory design would be to access id through getID(), though you'd need a setter as well as the existing getter method.

declaring a variable as private will give a result that only the class the variable is declared in can access it, if you want classes that inherit basic classes to be able to also access the variable, use protected.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top