0

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.

2
  • What exactly is your question? It looks like you understand it just fine in your code. Commented Dec 5, 2013 at 16:37
  • What don't you understand? private means that the member can only be accessed by name within member (and friend) functions of the class, which is exactly what's happening here. Commented Dec 5, 2013 at 16:39

2 Answers 2

3

C++ encapsulation is class based. Instances of a class can freely access private members of other objects of the same class.

Sign up to request clarification or add additional context in comments.

2 Comments

So do you mean, in the definition of class C, I can access the private members of objects created by the same class name ?
Yes, in functions defined in a class C you can access private members of all objects of class C, not only the object pointed to by pointer this.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.