I saw the following example somewhere and in that, the objects of the same class were able to access private members. I couldn't understand the logic behind it.
#include <iostream>
using namespace std;
class CTime
{
int hours;
int minutes;
public:
void getTime(int h, int m)
{
hours = h;
minutes = m;
}
void putTime(void)
{
cout << hours << "hours and ";
cout << minutes << " minutes" << "\n";
}
void sum(CTime t1, CTime t2);
};
// ---------- vvvv ---------------
// --------- Here ---------------
void CTime::sum(CTime t1, CTime t2)
{
minutes = t1.minutes + t2.minutes;
hours = minutes/60;
minutes = minutes%60;
hours = hours + t1.hours + t2.hours;
}
int main()
{
CTime T1, T2, T3;
T1.getTime(2, 45);
T2.getTime(3, 30);
T3.sum(T1, T2);
cout << "T1 = ";
T1.putTime();
cout << "T2 = ";
T2.putTime();
cout << "T3 = ";
T3.putTime();
return 0;
}
In sum(CTime, CTime) function, the objects of CTime are able to access the private members. In which scenario is it possible. Kindly clarify. Thank you.
privatemeans that the member can only be accessed by name within member (and friend) functions of the class, which is exactly what's happening here.