adplus-dvertising

Constructors and destructor of a class in C++

last news

Constructors and destructor of a class in C++

As a special member function of the class, a constructor is a function that initializes an object when it is created. In C++, the constructor is called automatically when an object (an instance of the class) is created.

It is important to note that constructors will have the same name as the class, and they will not have a return type, not even void. Constructors are useful in setting the initial values of certain data members.

In the absence of a constructor declaration, the C++ compiler generates a default constructor that expects no parameters and has an empty body.

There are three types of constructors in C++:

  •   Default Constructor
  •   Parameterized Constructor (Initialization constructor)
  •   Copy Constructor

Default Constructor

Default constructors take no arguments and have no parameters.

Example
#include <iostream>
using namespace std;

class Car{
    private:
        int NB_wheels;
        double speed;
        int mileage;
        int Id;
    public:
        Car(){
            Id = 1;
            NB_wheels = 4;
            speed = 120;
            mileage = 200000;
            cout << "I'm the default constructor" << endl;
        }
};

int main()
{
    Car c1;
    return 0;
}
Output
I'm the default constructor

It is generally the default constructor that provides default values to the data members.

Parameterized Constructor

A parameterized constructor is created by passing parameters to it. These arguments help initialize an object during its creation.

Use the parameters to initialize the object when defining the constructor body.

Example
#include <iostream>
using namespace std;

class Car{
    private:
        int NB_wheels;
        double speed;
        int mileage;
        int Id;
    public:
        Car(int myid, int mywheels, double myspeed, int mymile){
            Id = myid;
            NB_wheels = mywheels;
            speed = myspeed;
            mileage = mymile;
            cout << "I'm the Parameterized constructor" << endl;
        }
};

int main()
{
    Car c1(1, 4, 120, 150000);
    return 0;
}
Output
I'm the Parameterized constructor

A parameterized constructor requires the initial values to be passed to the constructor. The usual method of declaring an object may not work. The constructor can be invoked explicitly or implicitly.

Example
Car c1(1, 4, 120, 150000); // Implicit call
    Car c2= Car(2, 4, 110, 60000); // Explicit call
Using Initializer Lists to Initialize Fields

In the case of parameterized constructors, the initialization list is used to initialize the data members of a class. The list of members to be initialized is specified with the constructor in the form of a comma-separated list.

Example
#include <iostream>
using namespace std;

class Car{
    private:
        int NB_wheels;
        double speed;
        int mileage;
        int Id;
    public:
        Car(int myid, int mywheels, double myspeed, int mymile){
            Id = myid;
            NB_wheels = mywheels;
            speed = myspeed;
            mileage = mymile;
            cout << "I'm the Parameterized constructor" << endl;
        }

        void ride(){
            cout << "Car " << Id << " is on its way with a speed of " << speed << endl;
        }
};

int main()
{
    Car c1(1, 4, 120, 150000); // Implicit call
    Car c2= Car(2, 4, 110, 60000); // Explicit call

    c1.ride();
    c2.ride();
    
    return 0;
}
Output
I'm the Parameterized constructor
I'm the Parameterized constructor
Car 1 is on its way with a speed of 120
Car 2 is on its way with a speed of 110

For an example class Test, if you need to initialize multiple fields X, Y, Z, etc., you can use the same syntax and separate the fields with commas:

Example
Test(int a, int b, int c) : X(a), Y(b), Y(c){
 
}

Copy Constructor

The copy constructor is a member function that initializes an object using another object of the same class.

Copy constructors are used to:

  •  Create an object by initializing it with another object of the same type.
  •  It is possible to pass an object as an argument to a function by copying it.
  •  Returning an object from a function requires copying it.

The general function prototype of a copy constructor is as follows:

Syntax
className (const className & object); 
Example
#include <iostream>
using namespace std;

class Car{
    private:
        int NB_wheels;
        double speed;
        int mileage;
        int Id;
    public:
        Car(int myid, int mywheels, double myspeed, int mymile){
            Id = myid;
            NB_wheels = mywheels;
            speed = myspeed;
            mileage = mymile;
            cout << "I'm the Parameterized constructor" << endl;
        }

        Car(const Car &c){
            Id = c.Id;
            NB_wheels = c.NB_wheels;
            speed = c.speed;
            mileage = c.mileage;
            cout << "I'm the copy constructor" << endl;
        }

        void ride(){
            cout << "Car " << Id << " is on its way with a speed of " << speed << endl;
        }
};

int main()
{
    Car c1(1, 4, 120, 150000);
    Car c2= c1;

    c1.ride();
    c2.ride();

    return 0;
}
Output
I'm the Parameterized constructor
I'm the copy constructor
Car 1 is on its way with a speed of 120
Car 1 is on its way with a speed of 120
It is essential to have a copy constructor if the class contains pointer variables and dynamic memory allocations.
In C++, we can define multiple overloaded constructors.

Destructor of a class

The destructor in C++ is called when an object of a specific class is destroyed, either explicitly through the use of delete for dynamically allocated objects or implicitly by the end of its scope. The destructor has the same name as the class preceded by the tilde (~) symbol.

Before an object is destroyed, the destructor can perform cleanup operations such as releasing dynamically allocated memory or closing files.

The following is a basic example of a C++ destructor:

Example
#include <iostream>
#include <cstring>
using namespace std;

class Car{
    private:
        int NB_wheels;
        double speed;
        int mileage;
        int Id;
        char *brand;
    public:
        Car(int myid, int mywheels, double myspeed, int mymile, char *brd){
            Id = myid;
            NB_wheels = mywheels;
            speed = myspeed;
            mileage = mymile;

            int size = strlen(brd);
            brand = new char[size + 1];
            strcpy(brand, brd);
        }

        ~Car(){
            cout << "I'm the destructor" << endl;
            delete [] brand;
        }

        void ride(){
            cout << "Car " << Id << " is on its way with a speed of " << speed << endl;
        }
};

int main()
{
    Car c1(1, 4, 120, 150000, "BMW");
    c1.ride();
    return 0;
}
Output
Car 1 is on its way with a speed of 120
I'm the destructor

When a class does not specify a destructor, the compiler creates one for us. The default destructor is fine unless we have dynamically allocated memory or a pointer in the class. In order to avoid memory leaks, it is necessary to write a destructor to free allocated memory when a class contains a pointer to allocated memory.

Each class can contain only one destructor, preceded by a ~. It has no parameters and no return type.
Partager ce cours avec tes amis :
Rédigé par ESSADDOUKI Mostafa
ESSADDOUKI
The education of the 21st century opens up opportunities to not merely teach, but to coach, mentor, nurture and inspire.