expl0it3r
expl0it3r

Reputation: 335

Friend class accessing protected member only C++

class A;

class B {
private:
    int x = 3;
protected:
    int y = 4;
public:
    int k = 5;
};

I would like A to be able to access B's public and protected members, but not its private members.

I do not want A to derive from B.

-In my program, I have class A which manipulates class B. I have built a system using these two classes, and thus B should only be able to manipulate A's private variables through A's protected functions.

What is the most elegant way to do this? Is it good practice to lay expose the variables in such a way?

Upvotes: 3

Views: 2270

Answers (2)

einpoklum
einpoklum

Reputation: 131547

If you don't want to change B, you can create a sort of a proxy class:

class B {
private:   
  int x = 3;
protected: 
  int y = 4;
public:    
  int k = 5;
};

class C : public B {
  friend class C_Proxy;
  // constructors...
};

class C_Proxy {
public:
  friend class A;
  C_Proxy(C& c) : y(c.y), k(c.k) { }
private:
  int& y;
  int& k;
}

(You can also arrange C_Proxy to handle proxying constant B's but that's not the focus of the question.)

Upvotes: 0

Miguel
Miguel

Reputation: 2219

The only solution I can think of is to take advantage of the non-associativity of friends relationships. If you contain the private members of B in another class and make B its friend, it would work.

Here's an example of what I say.

class B{
    private:
        class private_of_B{
        private:
            friend class B;
            int x = 3;
        };
        private_of_B private_members;
        friend class A;
    
    protected:
        int y = 4;
    
    public:
        int k = 5;
};
class A{
    public:
        void f(B& b) const{
            cout << b.y << endl;
            // good
            cout << b.k << endl;
            // good
            cout << b.private_members.x << endl;
            // error
        }
};

Anyways, this workaround seems like bad design... maybe the best thing you can do is redesign your class architecture.

Also, you might find this question useful.

Upvotes: 1

Related Questions