Question

I'm in a method of a derived class, loosely as follows:

Class Base
{
   private:
     int variableIWantToAccess;

}

Class Derived : public Base
{

   public someMethod() {
        variableIWantToAccess++;   <<-----ERROR

}

How do I access the variable that's declared in the base class? I'm unable to access it because it is private.

Was it helpful?

Solution 2

Leave the field private and create a pair of protected getter / setter methods instead (for the same reasons you wouldn't expose a public field).

Class Base
{
   private:
     int variableIWantToAccess;

   protected:
     int GetVariable() { return variableIWantToAccess; }
     void SetVariable(int var) { variableIWantToAccess = var; }

}

OTHER TIPS

You should declare it as protected instead of private.
Protected members of a class are accessible for the class descendants only.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top