Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can you access private member variables across class instances?

Tags:

c++

I didn't think it was possible, but if you have two instances of the same class, are you allowed to access one's private members from the other?

Is this why you can also do this in copy constructors? in fact, is the copy constructor the reason this is allowed? Doesn't this break encapsulation?

like image 789
Dollarslice Avatar asked Nov 29 '22 03:11

Dollarslice


2 Answers

Yes, any code within a class can access private data in any instance of the class.

This breaks encapsulation if you think of the unit of encapsulation as the object. C++ doesn't think of it that way; it thinks of encapsulation in terms of the class.

like image 67
Ernest Friedman-Hill Avatar answered Dec 05 '22 13:12

Ernest Friedman-Hill


Access restrictions are a property of the class, not of an instance.

That's why you can write your usual copy constructor:

class Foo
{
     int a; // private!
public:
    Foo (Foo const & rhs) : a(rhs.a) { } // rhs.a is accessible
};

This idea is also what fuels the "factory" idiom:

class Bar
{
    Bar() { } // private?!
public:
    static Bar * create() { return new Bar(); } // Bar::Bar() is accessible
};
like image 37
Kerrek SB Avatar answered Dec 05 '22 12:12

Kerrek SB