Access specifiers in C++ - ProgrammerTech
Language:

Search

Access specifiers in C++

  • Share this:
Access specifiers in C++

C++ Access Specifiers

public variables and private variables. In the previous lessons, we made the Date, Persone, and Car classes, and learned how to add properties to the class.

In order to add these properties to each object of this class and we learned how to add a function.

The constructor function that runs at the beginning of the line in which you create the object from the class.

And we talked about private and public, and in this lesson we will talk more about private and public, what we need and how to deal with private variables.

The general form of a program containing the variables private and public

#include <iostream>
using namespace std;
class Time{
private:
//Elements that will not be accessed are placed by the main . function
public:
//The elements accessed by the function are placed from the main . function
};
int main()
{
        //Create the object that accesses the contents of the public
    return 0;
}

example 1

We will write an example of time because time contains three main elements, which are the hour, the minute, and the second.

#include <iostream>
#include <iomanip>
using namespace std;
class Time{
private:
        int hour;
        int minute;
        int second;
public:
        Time(int h, int m, int s)
        {
            hour = h;
            minute = m;
            second = s;
        }
        void print()
        {
            cout << setfill('0');
            cout << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second << endl;
        }
};
int main()
{
    Time time1(23,3,1);
    time1.print();
    return 0;
}

We created a class named Time and placed three private variables and three public variables in it.

And in the special variables, we have defined an int variable named hour, another variable named minute, and a third variable named second.

And in the global variables, we created a constructor with three variables defined as h, m and s, and passed them their definition values.

And we created a void function called print in order to call it to print via the object from inside main.

And we put the command to print and format on the screen via cout and we wrote setfill and we set it zero 0, that is, in the place of the spaces we put zeros.

And inside the print function we wrote setw(2) in order to put empty spaces, ie to format the DOS window.

And we entered the main function and created a time1 object and assigned it the values ​​of the variables, and then via the object we called the print function.

And when we run the code, we get the result.

23:03:01

We also note that the clock was printed for us in an organized and tidy manner, and if we remove the setfill command, its result will be unordered and there are spaces as in the figure.

23: 3: 1

As we have noticed from the previous image, we have been left with blank spaces between the timing of the clock, so what will we get if we remove the word setw(2) from the program and run it.

23:3:1

We noticed here that the empty spaces that were in the previous output window were removed and from here we understood why we put setw(2) and setfill and their importance in our example.

Now what if we want to change time1 to a different time.

We agreed that it is a good programming habit to set variables as private.

But if we write below the object by typing time1.hour=3 and we try to change the hour here when building the program, it will print an error as shown below.

access-specifiers-4.webp

We notice the red warning sign opposite line 27, which means that it is an error, because he does not know what an hour is because the hour at the top is defined as private.

And since it is private, it cannot be accessed outside of the class, and in the Time constructor, the hour can be changed. Therefore, we changed it by calling the constructor, but it cannot be accessed directly for several reasons, which are:

Not to access the hour value because its value can be sensitive.

And if we write, for example, time1.hour=55 in this way, it will change a variable whose value may reject this number. The hour cannot be equal to 55, as it sets some kind of limits.

No one who uses this class can access some sensitive values ​​that do not accept certain numbers. This is the first reason that we check the value before doing the equality.

So we can reach a solution. We don't have a public function, so why don't we make a function inside the class that changes the clock as a kind of circumvention of the law.

And since the functions can be accessed via main as the print function, we can write a second function that we access, for example the setHour function.

And we pass it the value 55 in this way the clock can be changed to 55 successfully.

And the function we created is called the Setters function, that is, it changes the value of the variables whose type is private at the top.

Example 2

Use the conditions and force the user to have the hours from 1 to 12 and the minutes from 0 to 60, as well as the seconds in order for the clock to be organized. Maybe a user is typing at 56, which doesn't make sense at all.

#include <iostream>
#include <iomanip>
using namespace std;
class Time{
private:
        int hour;
        int minute;
        int second;
public:
        Time(int h, int m, int s)
        {
            hour = h;
            minute = m;
            second = s;
        }
        void print()
        {
            cout << setfill('0');
            cout << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second << endl;
        }
        void setHour(int h)
        {
            if(h >= 1 && h <= 12)
                hour = h;
        }
        void setMinute(int m)
        {
            if(m >= 0 && m <= 60)
                minute = m;
        }
        void setSecond(int s)
        {
            if(s >= 0 && s <= 60)
                second = s;
        }
};
int main()
{
    Time time1(8,3,1);
    time1.setHour(55);
    time1.setMinute(20);
    time1.setSecond(0);
    time1.print();
    return 0;
}

We have created a setHour function for h which is of type int and we set a condition for it if h which stands for hours is less than or equal to 1 and if it is less than or equal to 12.

And we knew that the hour in the special variable as h stands for hours.

And we created the setMinute function for m minutes, which is of type int, and we set a condition for it. If m which stands for minutes is less than or equal to 0 and if it is less than or equal to 60 and we define the minute in the special variable as m to stand for minutes.

And we created a setSecond function for s minutes, which is of type int.

And we set a condition for it if the s symbolizing seconds is less than or equal to 0 and if it is less than or equal to 60.

And we defined the second in the special variable as s to stand for seconds.

Then in the main function we create the time1 object and assign values ​​to it.

Then we set a value for hours other than what we previously set for it, which is 55, a value for minutes is 20, and a value for seconds is 0.

We called the print function from the time1 object and when we run this program, the result will be the same.

08:20:00

We also note that the hours have not been changed to 55 as we told him because the hours are forced to be from 1 to 12.

As for the minutes, it was changed to 20 and the seconds were changed to 0, as we mentioned this to him in the conditions.

example 3

#include <iostream>
#include <iomanip>
using namespace std;
class Time{
private:
        int hour;
        int minute;
        int second;
public:
        Time(int h, int m, int s)
        {
            hour = h;
            minute = m;
            second = s;
        }
        void print()
        {
            cout << setfill('0');
            cout << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second << endl;
        }
        void setHour(int h)
        {
            if(h >= 1 && h <= 12)
                hour = h;
        }
        void setMinute(int m)
        {
            if(m >= 0 && m <= 60)
                minute = m;
        }
        void setSecond(int s)
        {
            if(s >= 0 && s <= 60)
                second = s;
        }
        int getHour()
        {
            return hour;
        }
        int getMinute()
        {
            return minute;
        }
        int getSecond()
        {
            return second;
        }
};
int main()
{
    Time time1(8,3,1);
    time1.setHour(55);
    time1.setMinute(20);
    time1.setSecond(0);
    time1.print();
    cout << time1.getHour() << endl;
    return 0;
}

We have created a new function setHour to invoke the hours of the same type as the variable.

Because it will return a value and the return value is the hour which in the variables private.

And we created a second function setMinute to call minutes, which is of the same type as the int variable because it will return the value from private which is minute.

And we created a third function for seconds, setSecond to call seconds and return us the value of second.

And in the main function, we put a print command on the output screen, which is time1.getHour, in order to print the clock only.

And here we have reached the watch that is in private and printed on the screen.

And when you run it will be as follows.

08:20:00
8

 

Lesson summary for private and public variables in C++

So, private is usually a good program in which all the variables in the class are written.

As for the public, we write all the functions we need to access in main.

When writing time1 and then a point, we will be able to access all functions and even variables of the public type.

As we said, it is good programming habits not to make the user control the variables directly, but rather to have a circumventional method. It changes the existing values ​​instead of accessing them directly after a little bit of checking the entered values.


Muhammad Alush

Muhammad Alush

إسمي محمد تركي العلوش من سورية من ريف حلب الشرقي 1994, محب للتقنية و التعلم الذاتي, و جميع خبراتي تعلمتها ذاتياً, و اللغات البرمجية التي أتقنها هي html, css, javascript, php, c, python بالإضافة إلى حبي الكبير لمجال الشبكات.

موقعي programmer-tech.com