-2

How can private variables be accessed in operator overloading (obj.real,obj.imag,res.real,res.imag) in this code. Can someone explain

#include<iostream>
using namespace std;

class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0)  {real = r;   imag = i;}

    // This is automatically called when '+' is used with
    // between two Complex objects
    Complex operator + (Complex const &obj) {
         Complex res;
         res.real = real + obj.real;
         res.imag = imag + obj.imag;
         return res;
    }
    void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
    Complex c1(10, 5), c2(2, 4);
    Complex c3 = c1 + c2; // An example call to "operator+"
    c3.print();
}
Niranjan Kotha
  • 289
  • 3
  • 14
  • 3
    What is the problem here? – Oliver Charlesworth Apr 09 '16 at 19:11
  • private members of a class are accessible only from within other members of the same class (or from their "friends"). But here real and imag are private variables and obj's real and imag values are accessed from outside the class – Niranjan Kotha Apr 09 '16 at 19:28
  • 1
    @NiranjanKotha: What are you talking about? No, they're not accessed from outside the class. You defined the operator as a member of the class. – Benjamin Lindley Apr 09 '16 at 19:34

2 Answers2

0

Your operator + should be able to access all private variables, because it's part of the same class. I see no problem here. But if you happened to have functions outside the class, you may use "friend" keyword (often used with streams). Do you have any errors from compiler?

Sia
  • 201
  • 1
  • 9
0

Access modifiers(public, private, protected) in C++ apply to the class as a whole, not individual objects. So if a class member is private, it is accessible by any member functions of that class, regardless of which object the member function is being called on.

And this isn't specific to operator overloading. It is applicable to all member functions.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274