Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access private members of class that is friends with parent class

Consider the following

class Base;

class A {
  int x;

  friend class Base;
};

class Base {
  protected:
    A a_obj;

  public:
    Base(){
      a_obj.x; // works
    }
};

class Derived : public Base {
  public:
    Derived(){
      a_obj.x; // not accessible
    }
};

I could make public getters and setters for x, or make the object public, but that is not preferrable. Assuming there is a bunch of derived classes, adding friend class Derived in class A would make the code too verbose. Is there a way to say "A is friends with class Base and all it's children"

like image 618
Trad_NotSuitedPC Avatar asked Jan 31 '26 05:01

Trad_NotSuitedPC


2 Answers

Is there a way to say "A is friends with class Base and all it's children"

No.

What you can do is make the base a friend (as you did), and write a protected accessor in the base that the children can use to access the private member.

like image 99
eerorika Avatar answered Feb 02 '26 20:02

eerorika


In short, c++ rule is that friendship is not inheritable. To achieve what you need, you can add static protected method as accessor in a Base class. But, if you really need to make it w/o accessors or getters you can make it with reinterpret_cast, but it would be hack and its not recommended.

like image 44
Boki Avatar answered Feb 02 '26 20:02

Boki