1
#include <string>
#include <iostream>
#include <vector>

using namespace std;

class Test {
public:
    int testing() {
        Test t;
        return t.x;
    }
private:
    int x = 0;

};

int main() {
    Test a;
    cout << a.testing() << endl;
}

I did not know I can access the private data member x of the t (the instance of Test that is not this) within the class definition of the Test. Why am I allowed to use t.x in the example code?

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
OneMoreGamble
  • 117
  • 1
  • 1
  • 5
  • 5
    If you could not access the private data within the class, how could you access it at all? – Passerby Oct 25 '21 at 22:26
  • It's really important when comes time to write comparison operators or move constructor/assignment –  Oct 25 '21 at 22:26
  • Are you asking why you can access `t.x` from `a` object? Or why you can access `private` members from method at all? For the former, see [With a private modifier, why can the member in other objects be accessed directly?](https://stackoverflow.com/questions/7396846/with-a-private-modifier-why-can-the-member-in-other-objects-be-accessed-directl) – Yksisarvinen Oct 25 '21 at 22:27
  • 1
    "I did not know" Well, why do you know that there is even such a thing as `private:`, or `class`, in the first place? *What does that source tell you* about how it works? "Why am I allowed to use "t.x" in the following code?" Well, did you think it should be possible to use `t.x` *anywhere*? If not, what is the point of having `int x = 0;` in the first place? How did you expect the code to look, that causes that value to change? What is the point of having data that you can't use? – Karl Knechtel Oct 25 '21 at 22:27
  • Any instance of `Test` can see and operate on all the data of any other instance of `Test` that it can get its grubby digital fingers on. – user4581301 Oct 25 '21 at 22:28
  • What would the point be of being able to declare a private variable in the class if you couldn't access it from within the class? I'm not sure that you really thought this through. – Ken White Oct 25 '21 at 22:29

1 Answers1

4

Colloquially, C++'s private is "class-private" and not "object-private".

Scopes are associated with lexical elements of source code, not with run-time entities per se. Moreover, the compiled code has little to no knowledge of the logical entities in the source it was compiled from. For this reason the accessibility is enforced on the level of lexical scopes only. Within the scope of the class, any object of the class's type can have its private members accessed.

Plus, C++ wouldn't be able to work as a whole otherwise. A copy constructor or an assignment operator could not be written if the accessibility was checked on a per-object basis. Those operations need to access the members of the source object in order to initialize/overwrite the target object.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458