Below code, shows a simple operator overloading for +
to a class Person. according to object encasulation, I should get an error when I access p.id
in operator overloading. Why I am not getting it ?
#include <iostream>
#include <vector>
using namespace std;
namespace friendDemo {
class Person {
private:
int id;
public:
int operator+(const Person& p);
Person(int id);
};
int Person::operator+(const Person& p) {
// accessing the private member
cout << p.id << endl;
return p.id + id;
}
Person::Person(int id) : id(id) {
cout << "Created" << endl;
}
void test() {
Person p1 {1};
Person p2 {2};
cout << "p1 + p2 = " << (p1 + p2) << endl;
}
};
int main() {
friendDemo::test();
return 0;
}
Output :
Created
Created
p1 + p2 = 2
3
Am I doing proper operator overloading? according to text, I should use friend function to access a private member, but his code is wired(without friend its accessing the private member)