C++ - Tutorial 007. Classes

C++, class

The availability of data that is publicly available in the structure has its advantages, providing complete freedom of action. However, we may want to hide the variables that are used in the data type to make the type behavior more predictable and easier to modify, and also that its usage is more like using a fundamental data type. To do this, you must define the interaction of the data type interface with access to inaccessible variables in the class.

In C ++, these types of data are called classes. A class has such a set of components as variables and methods for accessing the class's functionality.

The following sections can be defined in the class interface:

  • public - Methods and variables are available for interaction from outside the class;
  • protected - Methods and variables are available for use within the class, as well as in classes inherited from this class;
  • private - Methods and variables are available for use only within a class

However, private variables can be accessed externally using public methods.

In structures , you can also define private, protected, and public sections. The difference between structures and classes in this case is that by default all members of structures (variables, methods) are public, whereas in the class members are in the private section.

Let's see how the Vector class can look like, which was declared as a structure in the previous article .

class Vector 
    Vector(int s) 
        : elem {new double[s]}, 
    { }

    double& operator[](int i) { return elem[i]; }
    int size() { return sz; }

    double∗ elem; // Pointer to elements
    int sz; // Number of elements

Define a variable of class Vector .

Vector v(6); // Vector of six elements

Graphically, Vector can be represented thus:

In principle, Vector is an object that describes the work with a pointer to an array of elements and their magnitude. Different Vector objects can have different number of elements and their value, but the size of the Vector object will always be the same, since it stores only the pointer and the integer size of the array size.

Since the array of elements is now in the private section. That access to its elements will be made through the overloaded operator of square brackets [] , and to the size of the array via the size() method.

double read_and_sum(int s)
    Vector v(s);  // Create a vector of elements
    for (int i=0; i!=v.size(); ++i)
        cin>>v[i];  // We read the elements from the input and write them into the vector
    double sum = 0;
    for (int i=0; i!=v.size(); ++i)
        sum+=v[i];  // Summarize the elements
    return sum;

In the Vector class, there is a function with the same name as Vector(int) . This function is a Vector constructor that performs the necessary initialization actions for the object while it is being created. A class can have multiple constructors.

Vector(int s) 
    : elem {new double[s]}, 
{ }

In the constructor, the elements are initialized using the initializer list , which is an element of the C++11 standard.

It does not show the error handling mechanism and work with the destructor, but more on this later.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate

В функции

double read_and_sum(int s)

есть лишний пробел в
i!=v.siz e(); 

Спасибо, поправил.


Only authorized users can post comments.
Please, Log in or Sign up

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

Feb. 25, 2020, 4:40 a.m.

C++ - Test 005. Structures and Classes

  • Result:83points,
  • Rating points4
Feb. 24, 2020, 1:47 p.m.
Dmitrij Zlobin

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:40points,
  • Rating points-8
Feb. 17, 2020, 1:41 p.m.

C++ - Тест 003. Условия и циклы

  • Result:85points,
  • Rating points6
Last comments
Feb. 24, 2020, 2:54 a.m.
Evgenij Legotskoj

Добрый день. Там будет url, на который указывает ссылка тега a в пагинаторе, если правильно помню )) Написал этот код и забыл.
Feb. 23, 2020, 11:37 p.m.

Евгений Здравствуйте! Не могу понять вот эту часть кода: url: jQuery(this).attr('action') наверное здесь должен быть путь к url, тогда 'action' на какой url указывает?
Feb. 17, 2020, 2:22 a.m.
Evgenij Legotskoj

Добрый день. Это кастомный тег, помещается в файл, который находится в каталоге templatetags myapp/ templatetags/ myapp.py
Feb. 16, 2020, 12:36 p.m.

Добрый вечер! Монжно по подробней о теге get_companion? ссылка не работает.
Now discuss on the forum
Feb. 25, 2020, 7:06 a.m.

Feb. 24, 2020, 11:04 a.m.
Evgenij Legotskoj

Добрый день. Вот пример с дружественного ресурса с движением камеры
Feb. 24, 2020, 5:29 a.m.
Evgenij Legotskoj

Qt не предоставляет функционала по запросу root прав во время выполнения программы. Поэтому нужно использовать платформозависимый функционал, для Linux это будет выглядеть так: #include…
Feb. 24, 2020, 2:47 a.m.
Evgenij Legotskoj

Добрый день. Что означает клиентская область? Это изображение? Вам нужно распознавать символы текста или всё-таки пользователь будет вводить текст с клавиатуры, просто в любом месте "абстр…
Feb. 21, 2020, 4:19 a.m.
Vladimir Zhitkovsky

void sendImage(int sessid, int type, int dest, int format, QString imgBase64Data){ QNetworkRequest request; request.setUrl(QUrl(ipAddress + "ctlapi/cmd=preparereportimg&sessid=…
© EVILEG 2015-2019
Recommend hosting TIMEWEB