Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ protected access

Tags:

c++

is there anyway i can access a protected variable in a class without inheritance.

class ClassA{
  protected:
    int varA; 
};

class ClassB{
  protected:
    ClassA objectA;

};


ClassB theMainObject;

I would like to access varA through theMainObject.

like image 509
user346443 Avatar asked Aug 06 '26 23:08

user346443


1 Answers

You could make classB friend of classA

class ClassA{
  protected:
    int varA; 

  friend ClassB;
}

but using a accessors would probably be better since you are not coupling the classes together.

class ClassA{
  int getA() { return varA;}
  void setA(int a) { varA = a; }
  protected:
    int varA; 
}
like image 197
Rod Avatar answered Aug 08 '26 13:08

Rod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!