Evgenii Legotckoi
Evgenii LegotckoiJuly 8, 2017, 6:40 a.m.

C++ - Tutorial 007. Classes

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 
{
public:
    Vector(int s) 
        : elem {new double[s]}, 
          sz{s} 
    { }

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

private:
    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]}, 
      sz{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.

Do you like it? Share on social networks!

alex_lip
  • April 3, 2018, 4:09 a.m.

В функции

double read_and_sum(int s)

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

Evgenii Legotckoi
  • April 3, 2018, 5:06 a.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 4:56 a.m.

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

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 4:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 4:35 a.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
BlinCT
BlinCTMay 5, 2024, 5:46 a.m.
Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
BlinCT
BlinCTMay 5, 2024, 5:44 a.m.
добавить qlineseries в функции Давно я не работал с виджетами и с формами, на мой взгляд уже пережитов, и в управлении не очень удобное это все. Н оя у вас не увидел в коде где вы QCharts растягиваете на область парента.…
PS
Peter SonMay 3, 2024, 5:57 p.m.
Best Indian Food Restaurant In Cincinnati OH Ready to embark on a gastronomic journey like no other? Join us at App india restaurant and discover why we're renowned as the Best Indian Food Restaurant In Cincinnati OH . Whether y…
Evgenii Legotckoi
Evgenii LegotckoiMay 2, 2024, 2:07 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
IscanderChe
IscanderCheApril 30, 2024, 4:22 a.m.
Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…

Follow us in social networks