×
>
<

C++ Programming

C++ Constructor And Destructor | CrackEase

Constructor and Destructor in C++

Constructor and Destructor in C++

On this page we discuss constructors and destructors in C++. A constructor initializes an object when it is created (it can also allocate resources if needed). A destructor performs clean-up when an object is destroyed. Destructors are invoked automatically when an object goes out of scope or is deleted.

Constructor in C++

Constructors are special class functions used to initialize objects. The compiler calls a constructor automatically when an object is created.

  • If we create an object and don't initialize its members, they may contain indeterminate (garbage) values.
  • Constructors ensure members are initialized immediately when objects are created.
  • Constructors have the same name as the class and have no return type (not even void).

Syntax

Constructors can be declared inside the class or declared inside and defined outside the class using the scope resolution operator ::.

Inside the class

  
class A { 
  int i; 
  public: 
     A(){ 
       // Constructor declared and defined inside the class
       // assignments for initialization
       i = 0;
     }
};
  

Outside the class

  
class A
{
 int i;
 public:
     A(); 
     // Constructor declared
};

A::A()   // Constructor definition outside the class
{
    // initialization of values
    i = 1;
}
  

  1. Constructors have the same name as the class.
  2. They are called when an object is created (e.g., A obj;).
  3. They can be defined outside using the scope resolution operator ::.

Destructors in C++

Destructors are used to clean up resources when an object's lifetime ends. The compiler calls the destructor automatically when an object goes out of scope or is deleted.

  1. Destructors have no arguments and no return type.
  2. The destructor name is the class name prefixed with a tilde ~.

Syntax
  
class A
{
  public:
    ~A();
};
  

Example showing constructors and destructors together:

  
#include <iostream>
using namespace std;

class A
{
 public:
   A()
   {
     cout << "Constructor called" << endl;
   }
   ~A()
   {
     cout << "Destructor called" << endl;
   }
};

int main()
{
   A obj1; 
   // Constructor called for obj1
   int x = 1;
   if (x)
   {
      A obj2; 
      // Constructor called for obj2
   } 
   // Destructor called for obj2 as it goes out of scope here
   return 0;
}
// Destructor called for obj1 when main returns
  
Output
  
Constructor called
Constructor called
Destructor called
Destructor called
  
Footer Content | CrackEase