C++ Constructors and Destructors

Constructors and destructors are two special member functions of a class in C++ that are used to create and deconstruct the class’s objects, respectively.

Syntax for Constructor:

class ClassName {
   public:
      ClassName(); // default constructor
      ClassName(type1 arg1, type2 arg2, ...); // parameterized constructor
   private:
      // data members
};

ClassName::ClassName() {
   // default constructor body
}

ClassName::ClassName(type1 arg1, type2 arg2, ...) {
   // parameterized constructor body
}

Syntax for Destructor:

class ClassName {
   public:
      ~ClassName(); // destructor
   private:
      // data members
};

ClassName::~ClassName() {
   // destructor body
}

Example:

#include <iostream>
using namespace std;

class Car {
   public:
      // default constructor
      Car() {
         cout << "Default constructor called" << endl;
         speed = 0;
      }

      // parameterized constructor
      Car(int s) {
         cout << "Parameterized constructor called" << endl;
         speed = s;
      }

      // destructor
      ~Car() {
         cout << "Destructor called" << endl;
      }

      void setSpeed(int s) {
         speed = s;
      }

      int getSpeed() {
         return speed;
      }

   private:
      int speed;
};

int main() {
   // create objects of Car class
   Car car1; // default constructor called
   Car car2(100); // parameterized constructor called

   // set and get speed of car1
   car1.setSpeed(50);
   cout << "Speed of car1: " << car1.getSpeed() << endl;

   // set and get speed of car2
   cout << "Speed of car2: " << car2.getSpeed() << endl;

   return 0;
}

Output:

Default constructor called
Parameterized constructor called
Speed of car1: 50
Speed of car2: 100
Destructor called
Destructor called

In this illustration, the Vehicle class has a destructor, a parameterized function Object() { [native code] }, and a default function Object() { [native code] }. The speed data member is initially initialised to 0 by the default function Object() { [native code] }, to the supplied argument by the parameterized function Object() { [native code] }, and to the console by the destructor. Using the default function Object() { [native code] } on one and the parameterized function Object() { [native code] } on the other, we create two objects of the Car class. The setSpeed and getSpeed member functions are then used to control the automobiles’ speeds. The destructors of the objects are then called upon programme termination, printing messages to the console.