web analytics

Constructor & Destructor in C++

Constructor & Destructor

Constructor & Destructor

The syntax of constructor and destructor is the same. The constructor name is totally same as the class name and the class name is used for the name of the destructor, with a tilde ~ sign as the prefix to it.

What is Constructor?

  1. Constructor is a method.
  2. Constructor name must be same as the class name.
  3. Constructor is automatically called when the object is created.
  4. Constructor cannot be static.
  5. Constructor is an instance member.
  6. Constructor can take parameters.
  7. Constructor can be overloaded.
  8. Constructor is used to solve the problem of initialization.
  9. Constructor is used to make an object as real object.
  10. Constructor is used to avoid the garbage value in object.

What is Destructor?

  1. Destructor is a method.
  2. Destructor name is same as the class name followed by ~ mark.
  3. Destructor called automatically when object deallocate memory.
  4. Destructor cannot be static.
  5. Destructor is an instance method.
  6. Destructor does not take any parameter.
  7. Destructor cannot be overloaded.

Program with multiple constructors in a class?

using namespace std;
class Complex
      float real;
      float imag; 
       Complex()  // default constructor
         real = 0;                         
         imag = 0;
       Complex(float x) // 1 parameterised constructor
        real = x;                         
        imag = x;
      Complex (float x, float y)      // 2 parametrised constructor
        real = x;
        imag = y;
       void print()
        cout << this -> real << " + " << this -> imag << "j\n";
        Complex c1;
        Complex c2(10);
        Complex c3(10,20);


What is Copy Constructor?

The copy constructor is used to copy the field of one object to another object. The code snippet of the copy constructor is:

Complex (Complex &obj)
rela = obj.real;
imag = obj.imag;

What is dynamic constructor?

If a constructor allocates memory dynamically using new that constructor is known as dynamic constructor.

#include <iostream.h>
#include <conio.h>
class dynamic
 int * p;
  p=new int;
 dynamic(int v)
  p=new int;
 int dis()

void main()
dynamic o, o1(9);
cout<<"The value of object o's p is:";
cout<<"\nThe value of object 01's p is:"<<o1.dis();


The value of object o’s p is:10
The value of object 01’s p is:9

Related Posts

Leave a Reply

Your email address will not be published.