Evgenii Legotckoi
Evgenii LegotckoiJuly 8, 2017, 4:40 p.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, 2:09 p.m.

В функции

double read_and_sum(int s)

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

Evgenii Legotckoi
  • April 3, 2018, 3:06 p.m.

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

Comments

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

Qt - Test 001. Signals and slots

  • Result:68points,
  • Rating points-1
ЛС

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

  • Result:53points,
  • Rating points-4
АА

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

  • Result:60points,
  • Rating points-1
Last comments
ИМ
Игорь МаксимовOct. 5, 2024, 5:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 9:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssrFeb. 9, 2024, 5:43 a.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, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
Now discuss on the forum
MM
MichaelsusixQY MichaelsusixQYOct. 8, 2024, 3:57 a.m.
добавить qlineseries в функции Creating a healthier and healthier atmosphere is crucial for factories and factories. High-pressure washing can help remove contaminants, dust, and impurities that gather on floors, making sure …
JW
Jhon WickOct. 2, 2024, 1:52 a.m.
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
КГ
Кирилл ГусаревSept. 27, 2024, 7:09 p.m.
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
F
FynjyJuly 22, 2024, 2:15 p.m.
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

Follow us in social networks