Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow class access to single private member

I have a class A which has a private method called a(). I have also a class B which needs to access a() (but just B should have access to a(), thats why a() is private). I could now use a friend specifier but that would make other private methods of A (lets call them b() and c()) also available to B and I dont want that behaviour.

Is there a way to make just a() of A accessable to B?

like image 229
Sebastian Hoffmann Avatar asked Oct 19 '25 21:10

Sebastian Hoffmann


2 Answers

There is a way -- if your class has a public template function:

class A {
    // apparently private
    void priv () { std::cout << "got you A::a()" << std::endl ; }
public:
    template <class T> 
    void abuse() {}
    };


struct Thief {};

template <>
void A::abuse<Thief>() {
    this->priv();
    }

int main() {
    A a;
    // obviously do not compile :   a.priv();
    // this i OK
    a.abuse<Thief>();

    return 0;
    }

I must confess I stole this from GotW...

like image 138
reder Avatar answered Oct 22 '25 10:10

reder


No there's not, but as you specify the precise class, just B could access A's private members. You just have to take care of what method are called.

As friend relationship are not inherited, you don't have to worry about B's possible subclasses.

like image 23
Geoffroy Avatar answered Oct 22 '25 11:10

Geoffroy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!