How to access a protected member if we cannot change the class?

The third-party library class contains a protected member. How can I access it if we cannot change the code of a third-party library?

+3
source share
3 answers

Only a class, subclasses, or friend classes and methods can access a protected member. The only way to access the protected member is to subclass the class, and then use your subclass to protect the protected member.

For instance:

class parent {
  /* Other members */
  protected:
    int foo();
}


class child : public parent {
  public:
    int foo();
}
+8
source

You must make a special wrapper for this class. Just inherit the library class and gain access to protected members. Due to inheritance, you can use a wrapper class instead of a base class in the following code.

+3

You can access protected members from a derived class.

class A
{
  protected:
  int i;
};

class B : public A
{
  void func()
  {
    i; //valid
  }
};
+1
source

Source: https://habr.com/ru/post/1788777/


All Articles