An interesting thing about private members is that two objects of the same type can access each others private members freely. You can think of it as a class is always friends with itself. Since this is the constructor for ListData
and newlist
is also a ListData
, you can access its privates just fine.
Here's an example of this:
#include <iostream>
class foo
{
public:
foo() { }
foo(std::string secret) : secret(secret) { }
void steal_secret(const foo& other) { secret = other.secret; }
std::string get_secret() { return secret; }
private:
std::string secret;
};
int main() {
foo f1("I'm actually a bar");
foo f2;
f2.steal_secret(f1);
std::cout << f2.get_secret() << std::endl;
return 0;
}
f2
happily and easily steals the secret
from f1
, despite it being private.
The reason for this being allowed is simply because private
doesn't mean private to an object - it means private to a class. This eases the implementation of functions such as copy constructors that require doing some work to the internals of two objects of the same class.
The rule comes from the definition of private
(§11/1):
A member of a class can be
private
; that is, its name can be used only by members and friends of the class in which it is declared.
- [...]
Note that it is defined in terms of classes and not objects.