Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Allowing Access to Protected Members of Class and not Private Members

Tags:

c++

class

I know you can do this with inheritance, but you're meant to use inheritance for except for 'is a' circumstances. I also know there are friends, but they allow access to private members as well.

Is there any way of doing this (Allowing Access to Protected Members of Class and not Private Members)?

To reword the question, I have class 1 and class 2. I want class two to have access to class 1's protected and public members, but not it's private members. How would I do this?

like image 520
Jalfor Avatar asked Feb 21 '23 17:02

Jalfor


2 Answers

It's not elegant, but this might work for you:

class B;

class A {
protected:
    int x;
private:
    int y;
};

class A_wrapper : public A {
    friend B;
};


class B {
public:
    A_wrapper a;
    int foo() {
        a.x;   // Ok
        a.y;   // Compiler error!
    }
};
like image 89
Oliver Charlesworth Avatar answered Apr 28 '23 04:04

Oliver Charlesworth


Long ago, on this very website, I presented a scheme using a Key. The idea is that the main class documents which parts of the interface are accessible publicly and which necessitates a key, and then friendship to the key is granted to those who need it.

class Key { friend class Stranger; Key() {} ~Key() {} };

class Item {
public:
    void everyone();

    void restricted(Key);
private:
};

Now, only Stranger may use the restricted method, as is demonstrated here:

class Stranger {
public:
    void test(Item& i) {
        Key k;
        i.restricted(k);
    }

    Key key() { return Key(); }

    Key _key;
};

class Other {
    void test(Item& i) {
        Stranger s;
        i.restricted(s.key()); // error: ‘Key::~Key()’ is private
                               // error: within this context
    }

    void test2(Item& i) {
        Stranger s;
        i.restricted(s._key); // error: ‘Key::~Key()’ is private
                              // error: within this context
                              // error:   initializing argument 1 of ‘void Item::restricted(Key)’
    }
};

It is a very simple scheme which allows a much finer grained approach that full friendship.

like image 42
Matthieu M. Avatar answered Apr 28 '23 05:04

Matthieu M.