+ 2

Why am I allowed to access the private member in this object?

I truly feel like a noob for not knowing why this works, but the operator overload that I did in this C++ code works fine! (Yay?) But why is that? I wrote it expecting a compiler error. Basically I'm trying to access obj.balance... which is a private member in another object (obj). Since it's private, I figured I would NOT have access to it. I'd only have access to this->balance since "this" is the current instance that we're in, therefore we'd have access to our own private members. So why the heck does obj.balance not return a compiler error? Why am I able to access the private member of this other object? I mean, I'm glad it works but I want to understand it. :) class Account { private: int balance=0; int interest=0; public: Account() {} Account operator+(Account &obj) { Account mergedAccount = Account(); mergedAccount.balance = this->balance + obj.balance; mergedAccount.interest = this->interest + obj.interest; return mergedAccount; } };

1st Sep 2023, 5:37 AM
Pierre Gravelle
Pierre Gravelle - avatar
1 Antwort
+ 3
access qualifiers are not controlling access on the instance level, but on the type level. any member function of an instance of type T can access all the private members of any other instance of the very same type T. since the "operator+" is a member of your "Account" class. member functions can access any private members of that class, not only for this, but for any instance they can access.
1st Sep 2023, 7:37 AM
MO ELomari
MO ELomari - avatar