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?
When preceding a list of class members, the private keyword specifies that those members are accessible only from member functions and friends of the class. This applies to all members declared up to the next access specifier or the end of the class.
Private: The class members declared as private can be accessed only by the member functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of the class.
Which among the following is true? Explanation: The private members are accessible within the class. There is no restriction on use of private members by public or protected members. All the members can access the private member functions of the class.
Private Constructor is a special instance constructor present in C# language. Basically, private constructors are used in class that contains only static members. The private constructor is always declared by using a private keyword.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With