简体   繁体   中英

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"

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.

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.

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

No

You need to fix your design. Classes should not be granted access to members of all types derived from a base class. As per your code, I think you need to modify the private member of a class in the constructor of other class.

One possible solution is using parameterized constructor. You can call constructor of class A from classes Base and Derived .

class Base;

class A {
  int x;

public:
  A(int in): x(in)
  {

  }

};

class Base {
protected:
    A a_obj;

public:
    Base(int in): A(in)
    {

    }
};

class Derived : public Base {
public:
    Derived(): Base(5)
    {

    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM