I am learning OOP in C++ and I pretty much know most of the basics of it. But here is my query. I have learnt that we cannot access private data members from other objects. But I have a code snippet that seems to be doing so. It's working perfectly, but I want to know, why and how is this code working? Isn't it a violation of the OOP rules?
Here is the code:
#include "iostream"
using namespace std;
class Dist {
int feet; //private by default
float inches; //private by default
public:
void getdata()
{
cout<<"Enter the feets: ";
cin>>feet;
cout<<"Enter the inches: ";
cin>>inches;
}
void putdata()
{
cout<<"Data is "<<feet<<"\' "<<inches<<"\" "<<endl;
}
void add(Dist d)
{
this->feet = this->feet + d.feet;// accessing private data members!
this->inches = this->inches + d.inches;
if (this->inches >= 12) {
this->feet++;
this->inches = this->inches - 12;
}
}
};
int main()
{
Dist d1,d2;
d1.getdata();
d2.getdata();
d1.add(d2);
d1.putdata();
return 0;
}
How is this possible?