C++ Classes - ProgrammerTech
Language:

Search

C++ Classes

  • Share this:
C++ Classes

 Class concept in C++

A class is a new type defined by the word class and it can contain Functions, Variables, Arrays, etc.

Before we talk about classes, there is a very important concept that must be known first, which is abstraction.

Abstraction means anything that has been stripped of its qualities, and the meaning of the word abstraction is that it is free of appendages and contains empty titles clearly arranged.

 

Class and the benefit of abstraction

We have previously talked about variables in the first lessons and their types were (int, char, double, bool, string).

And we said that when we create a new variable, a special place is created for this variable in memory, and this variable has four properties (name, value, type, storage address).

If we want to store the date value for example Mar 23 1995 in memory, can the date be expressed as an int, a double, or a string.

 

How is the value of a particular date stored in memory?

First, we have to know what properties we want to store in history. Each date has a year, a month, and a day.

And from here we must know what variables should be created for any date, so we need three variables, which are:

  1. For the day int day.
  2. For the month int month
  3. For the year int year

And the variable type is int, we will take an example to understand this history more.

The general form of a class in C++

class Date{
    //Define the contents of the class
};

We note that we started the class name with a capital letter, and it is a good programming habit to start the class name with a capital letter.

Where it is differentiated from the variables and function.

Where if we want to define a variable, we write it in the form date in lowercase letters as a better programming habit, most programmers start the class name with a capital letter.

And at the end of the curly bracket we put a semicolon ; At the end of the function body, unlike the function like main, you don't need a comma at the end of the function body.

example 1

#include <iostream>
using namespace std;
class Date
{
public:
  int year;
  int month;
  int day;
};
int main ()
{
  Date birthday;
  birthday.year = 1995;
  birthday.month = 3;
  birthday.day = 23;
  cout << birthday.day << "/" << birthday.month << "/" << birthday.year << endl;
    return 0;
}

We created a class called Date, meaning the date class, and it had three global variables: year, month, and day.

And we entered the main function and we defined this class as a date of birth, and we set it the birthday object in order to access the contents of the class through it.

And we set a value for the year by accessing it through the object, and its value was 1995, and in the same order we assigned a value for the month and the day.

Then we built a cout print function and asked that it be printed for us at the beginning of the day and then separated by a slash / . Then it prints the month, then slash separates it, then prints the year, and when you run this code, the result will be the same.

23/3/1995

We also noticed from the previous execution screen that he printed the date of birth for us as we asked him to.

Example 2

Create a generic class containing two different birth dates.

#include <iostream>
using namespace std;
class Date
{
public:
    int year;
    int month;
    int day;
};
int main ()
{
    Date birthday;
    birthday.year = 1995;
    birthday.month = 3;
    birthday.day = 23;
    cout << birthday.day << "/"<<birthday.month<<"/"<<birthday.year<<endl;
    Date birthday2;
    birthday2.year = 1994;
    birthday2.month = 2;
    birthday2.day = 22;
    cout << birthday2.day <<"/"<<birthday2.month<<"/"<<birthday2.year<<endl;
    return 0;
}

We created a class called Date, meaning the date class, and it had three global variables: year, month, and day. This was in the class.

And we entered the main function and we defined this class as a date of birth and we put the birthday object for it in order to access the contents of the class through it.

And we set a value for the year by accessing it through the object, and its value was 1995, and in the same order we assigned a value for the month and the day.

Then we built a cout print function and asked that it print for us at the beginning of the day and then break it with a slash / then print the month and then slash separates it and then print the year.

And we created another object called birthday2 to access the contents of the class as on the first date.

And when you run the code, the result will be the same.

23/3/1995
22/2/1994

 

Using functions with classes

We recognize the class and say that it is an empirical method for formatting data by writing the variables used.

As in the date example, there is a variable for the day, a variable for the month, and a variable for the year.

But that's not all the class can do or store.

The class can store some functions that are specific only to this class and this is the principle of libraries.

As in the math library, where some functions are stored in the class, then all the functions stored in this class are listed.

We learned how to write the class and said that variables are now (only) public.

And under PUBLIC we write all the variables we want for any object we define of type Date.

When defining a new object, for example birthday, and when writing the name of the object and putting a period after it. We will find that autocomplete has brought us all the global variables that we have set in the above class.

We notice that there is a difference between an object and a class, here we are designing abstractly.

We just write what are the important properties of each date and each date has a year, month and day.

When creating any date, it will have a month, a day and a year, which means that the design or template is made.

As for the object, the application of the template is to have a living organism with values ​​for the elements in the class, when designing the class. Without writing the object it is as if there is no class in the program we are working with because we have not implemented this class.

As a work, such as designing a house, but there is no house on the ground, we just wrote the number of existing columns and the method of designing the columns.

Have we applied these columns in practice? Did you build a house? And if the answer is no, there is no home.

Likewise for the class and the object, if we do not write a variable of the class type, then this class does not exist in the memory, i.e. there is no variable for this class.

In short, an object is a variable that has values ​​stored in memory, the class is a template design for any variable of its type.

example 3

#include <iostream>
using namespace std;
class Date
{
public:
    int year;
    int month;
    int day;
    void print()
    {
        cout << day << "/" << month<<"/"<<year<<endl; cout
    }
};
int main ()
{
    Date birthday;
    birthday.year = 1995;
    birthday.month = 3;
    birthday.day = 23;
    birthday.print();
    Date birthday2;
    birthday2.year = 1994;
    birthday2.month = 2;
    birthday2.day = 22;
    birthday2.print();
    return 0;
}

We created a class called Date, meaning the date class, and it had three global variables: year, month, and day. This was in the class.

And it has a print function which is void print in order to call it to print what we need and we created a print function cout in order to print the format of this birth however we want.

And we entered the main function and we defined this class as a date of birth, and we put the birthday object for it in order to access the contents of the class through it.

And we set a value for the year by accessing it through the object and its value was 1995, and in the same order we assigned a value for the month and day.

Then we called the print function to print the output.

And we created another object called birthday2 to access the contents of the class in order to print the second birthday.

When you run this code, the result will be:

23/3/1995
22/2/1994

Example 4

#include <iostream>
using namespace std;
class Date
{
public:
    int year;
    int month;
    int day;
    void print()
    {
        cout << day << "/" << month << "/" << year << endl;
    }
    void fill(int d, int m, int y)
    {
        day = d;
        month = m;
        year = y;
    }
};
int main ()
{
    Date birthday;
    birthday.fill(23, 3, 1995);
    birthday.print();
    Date birthday2;
    birthday2.fill(22, 2, 1994);
    birthday2.print();
    return 0;
}

We created a class called Date, meaning the date class, and it had three global variables: year, month, and day. This was in the class.

And it has a print function called void print in order to call it to print what we need.

And we created a print function cout in order to print the format of this birthday however we want.

Then we created the fill function and put the variables in it, which are d, m and y, and we defined the variables’ abbreviations that d means day, m means month, and y means year.

And we entered the main function and created a birthday object, then we set values ​​for the first date by calling the fill function, and we put the date that is passed is 3/23/1995.

The same is true for the second child.

And upon implementation, the result was the same.

23/3/1995
22/2/1994

 

Constructor function in C++

A constructor is a function that is called automatically when creating an object from a class.

This function makes it possible for you to pass raw values ​​to the object right at the moment of its creation.

The constructor function is the first function called when creating an object of any class.

One of the most important tasks of this function is that it gives initial values ​​to all the variables in the class.

 

Constructor's Function Attributes

 

  • It does not return a value, not even void.
  • Its name comes the same as the class name (if the class name is Date, then its name is also Date).
  • It is called when creating any object directly from the class.

Example 5

Let's think about what is around us "smartphones and there are people" We will make a class that saves people. A person's name, age, height and height are considered important, we will make a class that saves the person's data.

#include <iostream>
using namespace std;
class Person
{
public:
    string name;
    int age;
    double height;
    Person(string n, int a, double h)
    {
        name = n;
        age = a;
        height = h;
    }
    void print()
    {
        cout << "The name " << name << endl;
        cout << "the age" << age << endl;
        cout << "Length" << height << endl;
    }
};
int main()
{
    Person saja("Saja", 27, 155.7);
    saja.print();
    return 0;
}

We created a class named Person and it had three global variables, a string to store the name in. and an int numeric variable to store the age in and a double to store the length in it.

Then we created a constructor, taking the same class name as Person, and defining it with the three variables. That the variable that symbolizes the name we abbreviate it with the letter n and the variable that symbolizes age with the letter a and the variable that symbolizes length h and then we define them.

And then we created a void function to print when it was called and we set it to print to the output screen via cout that prints the name and below the age and below the length.

Then we went inside the main function and created an object of the class name called saja and put inside the parentheses the values ​​that will be called and assigned to the three variables.

And we called the print function from the saja object.

And when implementing this program, we will get the following result.

Name: Saja
Age: 27
Length: 155.7

We also note that he printed the name Saja for us on top, then age 27, then height 155.7.

Example 6

Write a program that has a class called Car and has four variables for the car's name, color, speed and date of manufacture.

#include <iostream>
using namespace std;
class Car {
public:
    string name;
    string color;
    int speed;
    int model;
    Car(string name, string color, int speed, int model)
    {
        this->name = name;
        this->color = color;
        this->speed = speed;
        this->model = model;
    }
    void printInfo()
    {
        cout << "Name: " << name << "\n";
        cout << "Color: " << color << "\n";
        cout << "Speed: " << speed << "\n";
        cout << "Model: " << model << "\n";
    }
};
int main()
{
    Car car("BMW", "black", 240, 2001);
    car.printInfo();
    return 0;
}

We have created a class called Car and created four public variables:

  1. A text variable for the name of the car.
  2. Another text variant for the color of the car.
  3. An integer variable of the car's speed.
  4. Numerical variable for the date of manufacture or model.

And we created a constructor that took the same name as the class Car and passed data to it in order to recall it.

Then we set the values ​​to pass to the constructor.

And then we created a print function via void and the function is printInfo whose task is to print all the values ​​of the variables in the Car class.

And we went inside the main function, we derived an object from the class Car, and the object is car, and we put in it the values ​​that should be passed to the constructor directly.

And we called the print function from the object.

And when we run the previous code we will get the result.

Name: BMW
Color: black
Speed: 240
Model: 2001

 

Definition of functions outside the class

We will learn how to write the functions of a class outside the class.

Example 7

#include <iostream>
using namespace std;
class Student{
private:
    string name;
    double grade;
public:
    Student(string n, double g)
    {
        setName(n);
        setGrade(g);
    }
    void setName(string n)
    {
        name = n;
    }
    void setGrade(int g)
    {
        grade = g;
    }
    string pass()
    {
        return (grade > 60 ? "yes" : "no");
    }
    void printStatus()
    {
        cout << "Name : " << name << endl;
        cout << "Degree : " << grade << endl;
        cout << "Success : " << pass() << endl;
        cout << endl;
    }
};
int main()
{
    Student saja("Saja", 100);
    saja.printStatus();
    Student data("Mohammad", 30);
    data.printStatus();
    return 0;
}

We have defined a class named Student and it had two properties: name which is the name and its type is string and grade which is double.

And as we have already learned that all properties or variables are defined as private so that they are not accessed. And modifying their values ​​directly by functions outside the Student class, such as the main function.

Then in public we put all the function (all functions) and among these first functions is the constructor function.

And we have redefined the constructor constructor Student function by adding the parameters of the first parameter n and the second parameter g.

In order to change the name by calling the setName function, which is a better way to write the constructor, we use setName instead of writing name=n.

Also, we wrote setGrade, then the name will be defined in n and the Grade in g, which are two functions of type void.

And as we said, Setters are of type void and a parameter of the same type as the variable name is passed.

And the variable name is of type string, string n will be passed and name is set with this parameter and setGrade is also done in the same way.

Then we created a function called pass and it returns a string. This function checks if the grade is greater than 60 will print yes, i.e. successful.

Otherwise, it will print no precipitate.

And the printStatus function This function will print the name, degree and status whether it was successful or not.

Success will be printed from the pass function and in the main function we have defined an object named saja and this object was passing the value of Saja as the name and 100 as the degree.

Then the status will be printed by the object.

Then we created a data object and it was passing Mohammad as name and 30 as degrees and then printing the status for it.

Name: Saja
Degree: 100
Success: yes
Name: Mohammad
Degree: 30
Success: no

We notice that in the cout function we did not write Get because we did not need to call the Grade of any of the objects.

Let's rearrange the previous code. In previous lessons, we talked about a way to write only the function header, for example.

void printName()
{
Here we write the code
}

And we copy the code and paste it under the main, can we do that with the class functions?

We will notice that the functions of the class are somewhat large, and in some classes there may be many and large functions as well.

Can we short it out? Yes, we can simply copy all the functions in the public in the previous example and paste them outside the main.

Since main is not defined outside of it because this scope is outside all functions and outside the class as well.

But we want to define, for example, a function setName that belongs to the Student class. We can simply write.

Student::Student(string n, double g)

This way we can access the functions that we have defined.

At the top we cancel all function bodies and just keep the function vertices by adding a semicolon.

As we used to do above main, this is called the function prototype ie the header of the functions so that we only keep the address headers of some functions.

Outside the class, we define these functions, so we must write Student two points above each other, which we will do. By completing some functions of the Student class, it will allow us to write the name of the function.

The code will be in the form.

#include <iostream>
#include <iomanip>
using namespace std;
class Student{
private:
    string name;
    double grade;
public:
    Student(string n, double g);
    void setName(string n);
    void setGrade(int g);
    string pass();
    void printStatus();
};
int main()
{
    Student saja("Saja", 100);
    saja.printStatus();
    Student data("Mohammad", 30);
    data.printStatus();
    return 0;
}
    Student::Student(string n, double g)
    {
        setName(n);
        setGrade(g);
    }
    void Student::setName(string n)
    {
        name = n;
    }
    void Student::setGrade(int g)
    {
        grade = g;
    }
    string Student::pass()
    {
        return (grade > 60 ? "yes" : "no");
    }
    void Student::printStatus()
    {
        cout << "Name : " << name << endl;
        cout << "Degree : " << grade << endl;
        cout << "Success : " << pass() << endl;
        cout << endl;
    }

When we run this code we will get the result.

Name: Saja
Degree: 100
Success: yes
Name: Mohammad
Degree: 30
Success: no

We learned how to separate some functions from the design of the class to the outside of the class so that we complete the definition of functions outside the class.

In fact, this is the best way to design a class, and the first part of the program is called a class header.

We only define the existing variables and functions and do not write any code.

Inside the function we only define variables and define functions, and we do not write code or code that will be run only by definition.


Muhammad Alush

Muhammad Alush

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

موقعي programmer-tech.com