0

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)

ajayramesh
  • 3,576
  • 8
  • 50
  • 75
  • `operator+` in your example is a member function so it can access all the private fields just fine. If you overload some operator as a free function it would be required to be a friend to access non-public fields. – user7860670 Feb 17 '18 at 19:14
  • 1
    If you made a free standing function `int operator+(const Person& lhs, const Person& rhs)`, then that non-member function would have to be a friend in order to access the non-public fields (as per VTT's comment). – Eljay Feb 17 '18 at 19:16
  • 1
    The detail you miss is that your operators are member functions. And then there's the duplicate with its C++ answers – StoryTeller - Unslander Monica Feb 17 '18 at 19:16
  • @aschepler: I know that each member has the full access to the class members. – Raindrop7 Feb 17 '18 at 19:23

0 Answers0