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!

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.

Hey thank you Moschops for your reply!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.