Saturday, September 3, 2011

Constructor in C++ programs


Constructors are a special type of function whose body must be executed at the time of creating any object. Constructors are special because they have the same name as the class with no return type. A constructor body defines what occurs when an object of a class is created. However, if no explicit constructor is defined, compiler will supply a zero argument empty body constructor. So, to initialize the data members of an object we can use constructor.

#include< iostream.h >
#include< conio.h >
class Rect
{
private:
int len, br;
public:
void getData ()
{
cout<< endl<< "Enter Length and Breadth: -";
cin>>len>>br;
}
void setData (int l, int b)
{
len=l;
br=b;
}
void displayData ()
{
cout<< endl<< "Length="<< len;
cout<< endl<< "Breadth="<< br;
}
void area ()
{
int a, p;
a=len*br;
p=2*(len+br);
cout<< endl<< "Area="<< a;
cout<< endl<< "Perimeter="<< p;
}
Rect ()
{
}
Rect (int a, int b)
{
len=a;
br=b;
}
};
void main ()
{
clrscr ();
Rect r1 (2,3), r2, r3;
cout<< endl<< "For object number 1: -";
r1.displayData ();
r1.area ();
cout<< endl<< "For object number 2: -";
r2.setData (3,5);
r2.displayData ();
r2.area ();
cout<< endl<< "For object number 3: -";
r3.getData ();
r3.displayData ();
r3.area ();
getch ();
}

Here note that the constructor is defined twice in the class Rect. In this program this is a must, as the object r1 will be created after execution of the argument constructor and r2, r3 are created with the help of zero argument empty body constructor. In a class we can have two or more functions with the same name, as long as their parameter declarations are different. When this is the case the functions are said to be overloaded. Function overloading is an example of polymorphism.



No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner