Constructor in C++





Constructor in C++

Constructor is a member function with the same name as the name of a class. It is automatically called when an object of the class is created. It is used to initialize the objects of that class. They don’t have any return type.

Counter example using constructor.

#include<iostream.h>
#include<conio.h>
Class counter
{
Private:
Int count;
Public:
Counter ()        // constructor
{
Count=0;
}
Void inc_count ()
{
Count++;
}
Int get_count ()
{
Return count;
}
};
Void main ()
Counter c1;
Cout<<”\n c1.get_cout ();
C1.inc_count ();
getch ();
}

Need for constructor

It is a function used to initialize the object belonging to that class. The data within the class cannot b initialized at that time of declaration. This is because the declaration of a class serves only as a template, and no memory is allocated at the time of declaration. This problem can be solved by writing an initializing function – a constructor. Constructor is a basically a function used to initialize variables, to allocate memory and soon. This function will be automatically called as soon as an object is created. There is no need to call the function to initialize the variables.

E.g.

Take the date class for example. Assume that each time an object of the date is created, it is to be initialized with the date 01/01/2011.

#include<iostream.h>
#include<conio.h>
Class date
{
Private:
Int dd, mm, yy;
Public:
Date ()
{
dd=01;
mm=01;
yy=2011;
}
Void display ()
{
Cout<<”\n <<dd<<”\”<<mm<<”\””<<yy;
}
};
Void main ()
{
Date date1;
Date1.display ();
getch ();
}

In above example as soon as the object say date1 is created, the constructor will be called and the values dd, mm, yy initialized to the required date- 01/01/2011.



Related posts:

  1. Class In C++ Class in c++ Class is a group of similar object....
  2. Defining Member Function In C++ Class methods definitions  (Defining the member functions) Member functions can...
  3. C++ Functions C++ Functions A function is meant for performing a specified...
  4. Procedural oriented programming Procedural oriented programming (pop):- A program in a procedural language...
  5. Object oriented programming Object oriented programming : The main idea behind object oriented...