Thursday, February 17, 2011

Parameterized constructors


Parameterized constructors
The constructor consTest(), defined above, initialized the data member of all the objects to 100. However, in practice it may be necessary to initialize the various data elements of different values when they are created. C++ permits us to achieve this objective by passing arguments to the constructor function when the objects are created. The constructors that can take arguments are called parameterized constructors. A constructor may be defined with default arguments like function. The default constructor and constructor with default arguments are different things.
Example
Program to demonstrate the passing of arguments to the constructor

class rectangle
  {
   private:
      float length,breadth;
   public:
       rectangle(float l, float b)
              {  length=l;
              breadth=b;  }
     
     void area()
             { cout<<"\nThe area of rectangle is:"<<length*breadth;  }
       };

void main()
  {
  rectangle r1(10,20);       //constructor call implicitly
  rectangle r2=rectangle(20,30);     //constructor call explicitly
  r1.area();
  r2.area();
      }

Output Of The Program
The area of rectangle is:200
The area of rectangle is:600

No comments:

Post a Comment