0

Hi,

I was learning operator overloading and I noticed a very strange thing. I could access the private variable of another object by using the object reference and the . operator. Both the objects belong to the same class and I can alter the value of a private variable of object b by using its reference in the overloaded function for the + operator. Below is my code:

#include<iostream>

class complex{

private:
float real;
float imag;

public:

void display(void){
    std::cout<<real<<" + j"<<imag<<std::endl;
}   
complex(){
}
complex(float r, float i){
    real =r;
    imag=i;
}   

complex operator + (complex &); 

};
complex complex::operator +(complex &b){

    complex temp;
    temp.real = real + b.real;
    temp.imag = imag + b.imag;
    b.real=0;
    return (temp);

}
int main()
{
    complex a(3.14,3.14);
    a.display();
    complex b(1,1);
    complex c;
    c = a + b;
    b.display();
    c.display();

    return 0;
}

Why can I alter object b's variables when it is given that a invokes the operator+ function and passes parameter b implicitly to it??

Thanks in advance for your replies!

Edited by anumash

2
Contributors
2
Replies
13
Views
1 Year
Discussion Span
Last Post by anumash
0

In C++, protection is at the class level. A member function of a class can access the private variables of any instance of that class.

Edited by Moschops

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.