Last Updated:

Classes in C++

The entire real world is made up of objects. Cities consist of districts, each district has its own street names, on each street there are residential buildings, which also consist of objects.

Almost any material object can be represented as a set of objects of which it consists. Let's say we need to write a program to account for student performance. You can think of a group of students as a C++ class. Let's call it .Students

class Students {
     // Student name
     std::stringname;
     // Surname
     std::string last_name;
     // Five student grades
     intscores[5];
     // Final grade for the semester
     float average_ball;
};

Concepts

Classes in programming consist of properties and methods. Properties are any data that can characterize an object in a class. In our case, the object of the class is the student, and his properties are the name, surname, grades and average score.

Each student has a first and last name. Also, he has intermediate grades for the entire semester. We will write these estimates to an integer array of five elements. After all five grades have been graded, we will determine the student's average score for the entire semester – property.namelast_nameaverage_ball

Methods are functions that can perform any action on the data (properties) of a class. Add to our class a function that will determine the average score of the student's performance.calculate_average_ball()

  • The methods of a class are its functions.
  • The properties of a class are its variables.
class Students {
     public:
         // Function that calculates the average score
         void calculate_average_ball()
         {
             int sum = 0; // Sum of all scores
             for (int i = 0; i < 5; ++i) {
                 sum += scores[i];
             }
             // calculate the arithmetic mean
             average_ball = sum / 5.0;
         }

         // student name
         std::stringname;
         // Surname
         std::string last_name;
         // Five student grades
         int scores[5];

     private:
         // Final grade for the semester
         float average_ball;
};

The function simply divides the sum of all intermediate estimates by their number.calculate_average_ball()

Public and private access modifiers

 

All properties and methods of classes have access rights. By default, all the contents of a class are read/write only to the class. In order to allow access to class data from the outside, use the access modifier . All functions and variables that are after the modifier become available from all parts of the program.publicpublic

The private class data is placed after the access modifier. If there is no modifier , then all functions and variables are closed by default (as in the first example).privatepublic

Usually, all the properties of a class are made private, and its methods are made public. All actions with private properties of a class are implemented through its methods. Consider the following code.

class Students {
     public:
         // Set the average score
         void set_average_ball(float ball)
         {
             average_ball = ball;
         }
         // Get the average score
         float get_average_ball()
         {
             return average_ball;
         }
         std::stringname;
         std::string last_name;
         int scores[5];

     private:
         float average_ball;
};

We cannot directly access classified class data. You can only work with this data by using the methods of this class. In the example above, we use the function to get a student's average grade, and to give that grade.get_average_ball()set_average_ball()

The function takes an average score as a parameter and assigns its value to a closed variable. The function simply returns the value of that variable.set_average_ball()average_ballget_average_ball()

Student Progress Program

 

We will create a program that will take into account the progress of students in the group. Create a header file named students.h that contains the .Students

/* students.h */
#include <string>

class Students {
    public:
        // Set student name
        void set_name(std::string student_name)
        {
            name = student_name;
        }
        // Get student name
        std::string get_name()
        {
            return name;
        }
        // Set student last name
        void set_last_name(std::string student_last_name)
        {
            last_name = student_last_name;
        }
        // Get the student's last name
        std::string get_last_name()
        {
            return last_name;
        }
        // Set intermediate estimates
        void set_scores(int student_scores[])
        {
            for (int i = 0; i < 5; ++i) {
                scores[i] = student_scores[i];
            }
        }
        // Set the average score
        void set_average_ball(float ball)
        {
            average_ball = ball;
        }
        // Get the average score
        float get_average_ball()
        {
            return average_ball;
        }

    private:
        // Intermediate estimates
        intscores[5];
        // Average score
        float average_ball;
        // Name
        std::stringname;
        // Surname
        std::string last_name;
};

We've added new methods to our class and made all of its properties private. The function stores the student's name in the variable , and returns the value of that variable. The principle of operation of the functions is similar.set_name()nameget_name()set_last_name()get_last_name()

The function takes an array with intermediate estimates and stores them in a private variable.set_scores()int scores[5]

Now create a main.cpp file with the following content.

/* main.cpp */
#include <iostream>
#include "students.h"

int main()
{
    // Create an object of class Student
    student student;

    std::stringname;
    std::string last_name;

    // Entering a name from the keyboard
    std::cout << "Name: ";
    getline(std::cin, name);

    // Enter last name
    std::cout << "Last name: ";
    getline(std::cin, last_name);

    // Saving the first and last names in the Students class object
    student.set_name(name);
    student.set_last_name(last_name);

    // Grades
    intscores[5];
    // Sum of all scores
    int sum = 0;

    // Enter intermediate grades
    for (int i = 0; i < 5; ++i) {
        std::cout << "Score " << i+1 << ": ";
        std::cin >> scores[i];
        // summation
        sum += scores[i];
    }

    // Save intermediate grades to an object of class Student
    student.set_scores(scores);
    // Calculate the average score
    float average_ball = sum / 5.0;
    // Store the average score in an object of class Students
    student.set_average_ball(average_ball);
    // Display student data
    std::cout << "Average ball for " << student.get_name() << " "
         << student.get_last_name() << " is "
         << student.get_average_ball() << std::endl;

    return 0;
}

At the very beginning of the program, an object of the . The fact is that the class itself is only a description of its object. A class is a description of any of the students who have a first name, last name, and ability to receive grades.StudentsStudents

A class object characterizes a particular student. If we want to assign grades to all the students in the group, we will create a new object for each of them. The use of classes is very well suited for describing real-world objects.Students

After creating an object, we enter from the keyboard the surname, first name and intermediate grades for a particular student. Let it be Vasya Pupkin, who has five grades per semester – two triples, two fours and one five.student

We pass the entered data to set-functions, which assign them to private variables of the class. After the intermediate scores have been entered, we calculate the average score based on these scores, and then store this value in a closed property, using the function .average_ballset_average_ball()

Compile and run the program.

Separating data from logic

 

Let's put the implementation of all the methods of the class in a separate files students.cpp.

/* students.cpp */
#include <string>
#include "students.h"

// Set student name
void Students::set_name(std::string student_name)
{
    students::name = student_name;
}

// Get student name
std::string Students::get_name()
{
    return students::name;
}

// Set student last name
void Students::set_last_name(std::string student_last_name)
{
    Students::last_name = student_last_name;
}

// Get the student's last name
std::string Students::get_last_name()
{
    return Students::last_name;
}

// Set intermediate estimates
void Students::set_scores(int scores[])
{
    for (int i = 0; i < 5; ++i) {
        students::scores[i] = scores[i];
    }
}

// Set the average score
void Students::set_average_ball(float ball)
{
    Students::average_ball = ball;
}

// Get the average score
float Students::get_average_ball()
{
    return Students::average_ball;
}

And in the header file students.h we will leave only the prototypes of these methods.

/* students.h */
#pragma once /* Protect against double header file inclusion */
#include <string>

class Students {
    public:
        // Set student name
        void set_name(std::string);
        // Get student name
        std::string get_name();
        // Set student last name
        void set_last_name(std::string);
        // Get the student's last name
        std::string get_last_name();
        // Set intermediate estimates
        void set_scores(int[]);
        // Set the average score
        void set_average_ball(float);
        // Get the average score
        float get_average_ball();

    private:
        // Intermediate estimates
        intscores[5];
        // Average score
        float average_ball;
        // Name
        std::stringname;
        // Surname
        std::string last_name;
};

This approach is called data abstraction, one of the fundamental principles of object-oriented programming. For example, if someone else wants to use our class in their code, they don't necessarily need to know how the GPA is calculated. He will simply use the function from the second example, without delving into the algorithm of its work.calculate_average_ball()

Several programmers usually work on large projects. Each of them is engaged in writing a certain part of the product. At this scale of code, it is almost impossible for one person to remember how each of the internal functions of the project works. In our program, we use the stream output operator without thinking about how it is implemented at a low level. Also, separating data from logic is good programming tone.cout

At the beginning of the tutorial, we talked about namespaces. Each class in C++ uses its own namespace. This is done in order to avoid conflicts when naming variables and functions. In the file, we use an affiliation operator before the name of each function. This is done in order to indicate to the compiler that these functions belong to the class .students.cpp::Students

Creating an Object through a Pointer

When creating an object, it is better not to copy the memory for it, but to allocate it to the heap using a pointer. And release it after we've finished working with the object. We implement this in our program by slightly changing the contents of the main.cpp file.

/* main.cpp */
#include <iostream>
#include "students.h"

int main()
{
    // Allocate memory for the Students object
    students *student = new students;

    std::stringname;
    std::string last_name;

    // Entering a name from the keyboard
    std::cout << "Name: ";
    getline(std::cin, name);

    // Enter last name
    std::cout << "Last name: ";
    getline(std::cin, last_name);

    // Saving the first and last names in the Students class object
    student->set_name(name);
    student->set_last_name(last_name);

    // Grades
    intscores[5];
    // Sum of all scores
    int sum = 0;

    // Enter intermediate grades
    for (int i = 0; i < 5; ++i) {
        std::cout << "Score " << i+1 << ": ";
        std::cin >> scores[i];
        // summation
        sum += scores[i];
    }
    // Save intermediate grades to an object of class Student
    student->set_scores(scores);

    // Calculate the average score
    float average_ball = sum / 5.0;
    // Store the average score in an object of class Students
    student->set_average_ball(average_ball);
    // Display student data
    std::cout << "Average ball for " << student->get_name() << " "
         << student->get_last_name() << " is "
         << student->get_average_ball() << std::endl;
    // Removing the student object from memory
    delete student;
    return 0;
}

 

When creating a static object, to access its methods and properties, use the direct access operation - "." (dot symbol). If the memory for the object is allocated by means of a pointer, then the indirect inversion operator "->" is used to access its methods and properties.

Class Constructor and Destructor

 

A class constructor is a special function that is automatically called as soon as an object of that class is created. It has no return type and must be named the same as the class in which it resides. By default, fill in the array with intermediate grades of the student with twos.

class Students {     public:
         // Students class constructor
         students(int default_score)
         {
             for (int i = 0; i < 5; ++i) {
                 scores[i] = default_score;
             }
         }

     private:
         int scores[5];
};

int main()
{
     // Passing a 2 to the constructor
     Students *student = new Students(2);
     return 0;
}

We can correct the deuces if the student behaves well, and take homework on time. And there is no court for "no" :-)

The class destructor is called when an object is destroyed. The name of the destructor is similar to the name of the constructor, only at the beginning is the tilde sign ~. The destructor has no input parameters.

#include <iostream>

class Students {
    public:
        // 
        ~Students()
        {
            std::cout << "Memory has been cleaned. Good bye." << std::endl;
        }
};

int main()
{
    Students *student = new Students;
    // 
    delete student;
    return 0;
}