Thursday, February 17, 2011

Multiple constructors in a class (Overloaded Constructors)


Multiple constructors in a class (Overloaded Constructors)
When more than one constructor function defined in a class, then we say that the constructor is overloaded.

#include <iostream.h>
#include <conio.h>
class rectangle
{
   private:
      float length,breadth;
   public:
     rectangle()  //constructor declared without argument
       { length=0;
             breadth=0;
                }

   rectangle(float side) //constructor declared with one argument
              {  length=side;
                 breadth=side;
                         }

    rectangle(float l,float b)       //constructor declared with two arguments
            {       length=l;
                        breadth=b; }
            void calculateArea()
                {  cout<<"\nThe area is\t :"<<(length*breadth);  }
 };

int main()
{
   rectangle r1;    //call constructor rectangle()
   rectangle r2(10); //call constructor rectangle(float side)
   rectangle r3(10,30);//call constructor rectangle(float l, float b)
     r1.calculateArea();
     r2.calculateArea();
     r3.calculateArea();
     }

Output:
The area is       : 0
The area is       : 100
The area is       : 300

1 comment: