Edouardos Kim
Edouardos Kim

Reputation: 169

Able to access private object member outside of class definition

It seems that my code goes against the rule that private members of an object can't be accessed outside of the class definition.

I have a class define like so

class Test{
private:
    int x;
public:
    const Test& operator=(const Test &other){
        this->x = other.x;
        return *this;
    }
    void addX(int);
    void getX();
};

What confuses me here is that I'm able to access private members of the object 'other' of class Test

This doesn't seem right or if it is, there must something fundamental I'm missing

Upvotes: 3

Views: 906

Answers (3)

SergeyA
SergeyA

Reputation: 62613

Yes, this is how C++ standard dictates it. However, I agree that it might be not what you expect.

To get your head around it, you might want to remember that access checks are compile-time checks - they are happening when the program compiles, not when it executes.

Now, let's consider your very example:

const A& operator=(const A& a) {
    x = a.x;
    return *this;
}

Now, when compiling this function, compiler (generally, let's pretend inlining is not happening) has no way of knowing if A& is the same as this object or not, because it could be called as

A a;
a = a;

Bottom line - even if we wanted to, we wouldn't be able to make an access modifier check take the class instance into account.

Upvotes: 4

Nellie Danielyan
Nellie Danielyan

Reputation: 1011

As stated in cppreference

A private member of a class can only be accessed by the members and friends of that class, regardless of whether the members are on the same or different instances:

class S { private: int n; // S::n is private public: S() : n(10) {} // this->n is accessible in S::S S(const S& other) : n(other.n) {} // other.n is accessible in S::S };

Upvotes: 3

Fire Lancer
Fire Lancer

Reputation: 30165

You can access private (and protected) members of any instance for the same type. This includes static members, and private or protected inherited bases.

A couple of examples:

class Base {
protected:
    int y;
private:
    int z;
};
class Sub;
class Test : private Base {
private:
    int x;
public:
    const Test& operator=(const Test &other) {
        this->x = other.x; // Can access private members for any instance
        this->y = other.y; // Can access a protected member of a base type
        this->z = other.z; // ERROR: Neither side is OK, can't access a private member of a base
        return *this;
    }
    void foo(Sub &sub);
};
class Sub : public Test
{
private:
    int w;
};
inline void Test::foo(Sub &sub) {
    int a = sub.x; // Still OK, as x is a member of Test
    a += sub.w; // ERROR: Can't access privates of subtypes however
}

Upvotes: 6

Related Questions