Reputation: 1064
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.
Upvotes: 0
Views: 111
Reputation: 75874
This is a very good basic explanation http://www.cplusplus.com/doc/tutorial/inheritance/
You will find there, among others, a table with access types. This is what interests you, but the whole article is useful.
Upvotes: 1
Reputation: 26204
C++ encapsulation is class based. Instances of a class can freely access private members of other objects of the same class.
Upvotes: 3