C++ Constructor overloading

Like methods constructors can also be overloaded since the constructor in a class have the same name as that of the class their signatures are differentiate as their parameter list. Overloading of constructor allows appropriate initialization of objects on creation, depending upon the constructors allow specifying or initializing the data members dynamically.

Program:

/*PROGRAM TO IMPLEMENT CONSTRUCTOR OVERLOADING*/

#include<iostream.h>

#include<conio.h>

class rectangle

{

int length,breadth;

public:

rectangle()

{

length=breadth=0;

cout<<“**Constructor with zero argument

called**”<<endl<<endl;

}

rectangle(int a)

{

length=breadth=a;

cout<<“**Constructor with one argument

called**”<<endl<<endl;

}

rectangle(int l,int b)

{

length=l;

breadth=b;

cout<<“**Constructor with two arguments

called**”<<endl<<endl;

}

int area()

{

return(length*breadth);

}

};

void main()

{

clrscr();

rectangle r1;

cout<<“\tArea of rectangle zero arguments is:

“<<r1.area()<<endl<<endl;

rectangle r2(5);

cout<<“\tArea of rectangle with one argument is:

“<<r2.area()<<endl<<endl;

rectangle r3(11,12);

cout<<“\tArea of rectangle with two arguments is:

“<<r3.area()<<endl<<endl;

getch();

}

Leave a Reply

Your email address will not be published. Required fields are marked *