I am a little confused about private data members in C++ classes. I am new to coding and still in the middle of my 'Classes' chapter so I might be ahead of myself, but I feel like I am missing a piece of information:
Let's say I have this code:
class clocktype;
{
public:
void setTime(int,int,int);
.
.
.
private:
int hr;
int min;
int sec;
};
And I create a object myclock.
clocktype myclock;
myclock::setTime(hour,minute,min)
{
if (0<= hour && hour < 24)
hr = hour;
if (0<= minute && minute <60)
min = minute;
if ( 0<= second && second<60)
sec = second;
}
myclock.setTime(5,24,54);
My textbook says I can't do this:
myclock.hr = 5;
because hr
is a private data member and object myclock
has only access to the public members. But isn't that practically what I am doing in my setTime
function anyways? I understand I am accessing myclock.hr
through my public member function. But I am still struggling with the logic behind that. What does it mean to be a private data member then?
myclock.hr = 5
would let you sethr
to anything. YoursetTime
function is placing restrictions on the values you can set it to. It's maintaining an invariant. – Pericline