Vladimir Yanakiev Vladimir Yanakiev - 1 month ago 16
C++ Question

Access to specific private members from specific class

I have a class

class A
{
.....
private:
int mem1;
int mem2;
}


I have another class B which need to access only to mem1.

class B
{
....
}


How can I access private member mem1 from only from class B? I don't want to use friend. This means access to all private members.

Answer

With some rearrangement to class A (which might not necessarily be acceptable), you can achieve this:

class Base
{
    friend class B;
    int mem1;
};

class A : public Base
{
    int mem2;
};

This exploits the fact that friendship is not transitive through inheritance.

Then, for class B,

class B
{
    void foo(A& a)
    {
        int x = a.mem1; // allowed
        int y = a.mem2; // not allowed    
    }
};