Constructor And Destructor In C++ Basics Of OPPS Concepts Explained

Here we will see about Constructor. In that what is constructor,it’s types,use of constructor and some characteristics of constructor.

What Is Constructor?

Constructor is a special member function that constructs an object.In other words we can say Constructor initialize the objects of class.

The first responsibility of constructor is to calculate the memory requirement of an object and allocate the space for its data members.

How to Declare and Define The Constructor

Consider the following example,

class Number

{

int num;

public:

Number()   // constructor declared

{

num=0;

}

void show()

{

cout<< num <<“\n”;

}

};

void main()

{

Number N1; // class name  Variable(object)

N1.show();

}

In above example Number() is a constructor that construct the values of data members of the class.

Types of Constructor

  1. Default Constructor
  2. Copy Constructor
  3. Parametrized Constructor

Default Constructor has no argument,we write this constructor with default parameter.A Constructor that takes the parameters through dummy arguments is called Parametrized Constructor.The constructor that construct an object from some another object of same class is called Copy Constructor.

eg.  class Complex

{

float x;

float y;

public:

Complex()       // default constructor

{

x=0;

y=0;

}

Complex( float a,float b)   // parameterized constructor

{

x=a;

y=b;

}

void show()

{

cout<<x<<y<<“\n”;

}

};       // end of class

void main()

{

Complex P1;

P1.show();    // it displays output 0  0,as x=0 & y=0

Complex P2;

P2.show(6,12);  // it displays output 6  12.

}

Properties/Characteristics of Constructor

This function have some properties.

  • It must have exactly the same name as of the class.
  • Constructor do not have any return type,not even void also.
  • It should declared in public section.
  • We cannot have virtual constructor.
  • When we create the object,the constructors are automatically invoked.

Destructor

It is a special member function that destroy the object.It is opposite to constructor,the dectructor gets called before some objects gets destroyed.

Destructor also has the same name as of class name,but only the difference is destructor name should be preceded with the sign tilda(~).

syntax:  ~ classname();

The objects are always destroyed in the reverse order of their creation.

Number of View :819
  1. No comments yet.

SetPageWidth
Content Protected Using Blog Protector By: PcDrome.

Mahol Dot Org is Stephen Fry proof thanks to caching by WP Super Cache