Hi Deesha,
I have got the answer. Let's go back to the definition of 'private' variable
A 'private' data member or member function can only be accessed by functions that are members of that class. It cannot be accessed by any function that is not a member function of that class.
note the use of word 'class' which means that 'private' is class private and
NOT object private as both of us were assuming till now.
Probably, the rationale behind this is that any objects of that class can easily access that variable by simply using a get function for that variable. Moreover, in case of operator overloading, just look at the advantage of this:
class A
{
public:
A(int _a){a = _a; b=0;}
A(int _a, int _b){a = _a; b = _b;}
int modify(A& obj2)
{
obj2.a = 707; //this no longer surprises me. :happy:
return obj2.a;
}
bool operator== (const A& obj2)
{
if( a == obj2.a && b == obj2.b)
return true;
return false;
}
A& operator+ (const A& obj2)
{
a += obj2.a;
b += obj2.b;
return *this;
}
int getValueA(){return a;}
int getValueB(){return b;}
private:
int a, b;
};
void main()
{
A obj1(2);
A obj2(10, 18);
if(obj1 == obj2)
cout<<"Equal";
cout<<"a = "<<obj1.getValueA()<<"\n";
cout<<"b = "<<obj1.getValueB()<<"\n";
obj1 = obj1+obj2;
cout<<"a = "<<obj1.getValueA()<<"\n";
cout<<"b = "<<obj1.getValueB()<<"\n";
}
Just look how in-convenient, not to mention the unnecessary function calls, it would have been to call getter function for each of the private variables inside operator overloading functions.
Also, making private vars as class private may also depend on internal implementation of private variables also.
More often than not, we are so much engrossed with public accessor/mutator that we use them even to access variables among objects!! At least, that's what I was doing for past so many years. 😒
You sure are on right track to learning C++. you may find #-Link-Snipped-# helpful.
Happy Learning and keep questioning (on CE )!