1

Suppose I have the following class:

class Test
{
             int num;
     public:
             Test(int x):num(x){}
             Test(const Test &rhs):num(rhs.num+1){}
};

int main()
{
      Test test(10);
      Test copy = test;
}

The num in the copy should be 11, and my question is about inside the copy constructor, why can we access the private member num of test using num to initialize the num in the copy? What is confusing me is that if you type cout<<test.num<<endl, of course it's wrong because you are trying to access the private num, but if you pass the test by reference to the copy constructor, it works, can anybody tell me what is going on here?

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
user1629199
  • 21
  • 1
  • 4
  • , what confusing me is that if you type like "cout< – user1629199 Aug 30 '12 at 03:01
  • Your english is not great, but suffices to get the point across. If you ask me, I would try to keep sentences shorter and avoid going over the same point multiple times. Also, when writing code in a question, surround it with back ticks \` to have it formatted as code and escaped (avoid the parser from interpreting ` – David Rodríguez - dribeas Aug 30 '12 at 03:04
  • thank you for your suggestion, I am trying to improve my English and learning everything – user1629199 Aug 30 '12 at 03:18
  • Good Read: [What are access specifiers? Should I inherit with private, protected or public?](http://stackoverflow.com/questions/5447498/what-are-access-specifiers-should-i-inherit-with-private-protected-or-public) – Alok Save Aug 30 '12 at 03:22

3 Answers3

6

Private members are private to the class itself, not the instances of the class.

VoidStar
  • 581
  • 3
  • 6
3

Access limitations are per-class, not per-object.

"private" means -- can only be accessed from within the same class.

"protected" means -- can be accessed from within the same class, and can also be accessed from within derived-classes (in derived classes, protected non-static members can only be accessed through variables with derived class type).

"public" means -- can be accessed by anything.

The point of access limitations is to limit the region of code that has to be inspected in order to understand where the values are used, rather than to stop code from using the values.

Mankarse
  • 39,818
  • 11
  • 97
  • 141
1

private doesn't mean private to the object instance. It means private to that class. An instance of a class T can access private members of other instances T. Similarly, a static method in a class T can access private members of instances of T.

If private restricted access to only the individual instance, it would make objects non-copyable, since as you pointed out, the copy constructor would not be able to read data from the original instance.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204