c++privatemembers

What does it mean to be a private member (c++ classes)?


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?


Solution

  • The main idea here is encapsulation. Differentiating between a private data member and a public setter method will allow you to change the implementation of your clocktype class and not requiring everyone that uses it to recompile their code. Let's say, for argument's sake, that you decide to change the clocktype implementation to store the number of seconds from the beginning of the day. All you need to do is reimplement the setTime method, and you won't have to touch the public interface:

    class clocktype;
    { 
        public:
            void setTime(int,int,int);
        private:
            int secFromMidnight;
    };
    
    clocktype myclock;
    myclock::setTime(hour, minute, second)
    {
        secFromMinight = second + (minute * 60) + (hour * 24 * 60);
    }