Constructor & Destructor in C++ | Basic IT Topic

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?

#include"iostream"
using namespace std;
class Complex
{         
private:
      float real;
      float imag; 
public:
       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";
       }
};
main()
{
        Complex c1;
        Complex c2(10);
        Complex c3(10,20);

        c1.print();
        c2.print();
        c3.print();
}

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;
 public:
 dynamic()
 {
  p=new int;
  *p=10;
 }
 dynamic(int v)
 {
  p=new int;
  *p=v;
 }
 int dis()
 { 
return(*p);
 }
};

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

Output:

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

basicittopic

basicittopic

A Computer Science Study for IT students and people of IT community