C++ Constructor and Destructor Example Program

Beginner

Introduction

In this lab, we will learn how to demonstrate the concept of Constructor and Destructor in C++ programming. We will develop a program to define a class called Rectangle and utilize Constructor and Destructor to initialize and destroy the class objects.

Create a new C++ source file

Navigate to the ~/project directory and create a new C++ source file called main.cpp using the command:

touch main.cpp

Define the Rectangle class

Define a class called Rectangle and add two public attributes length and breadth to it.

#include <iostream>

using namespace std;

//Rectangle class to demonstrate the use of Constructor and Destructor in CPP
class Rectangle {
    public:
        float length, breadth;

    //Declaration of the default Constructor of the Rectangle Class
    public:
        Rectangle() {
            cout<<"Constructor Called"<<endl;  //displaying the output when called
            length = 2;
            breadth = 4;
        }

    //Declaration of the Destructor of the Rectangle Class
    public:
        ~Rectangle() {
            cout<<"Destructor Called"<<endl;  //displaying the output before destruct
        }
};

Create a Class Object

Create an object of the class Rectangle. This will call the default constructor to initialize the object.

int main() {

    Rectangle rect;  //declaring an object of class Rectangle

    return 0;
}

Print Object Properties

Print the Length and Breadth of the Rectangle object using the object created in the previous step.

int main() {

    cout<<"Length of the Rectangle: "<<rect.length<<endl;

    cout<<"Breadth of the Rectangle: "<<rect.breadth<<endl;

    return 0;
}

Compile and Run the Program

Compile the program using the command below and execute the program by running the compiled executable:

g++ main.cpp -o main && ./main

Summary

In this lab, we learned how to demonstrate the concept of Constructor and Destructor in C++ programming. We defined a class called Rectangle and used the default constructor and destructor to initialize and destroy the class objects. We also printed the properties of the Rectangle object. The constructor was called when an object of a class was created while the destructor was called when the object was destroyed.

Other Tutorials you may like