Saturday 2 October 2010

Parameterized constructors:



PARAMETERIZED CONSTRUCTORS:

Constructors that take parameters are called as parameterized constructors. It is important to notice that if the parameterized constructor is provided then the compiler will not provide a default constructor.  In such cases, the following statement will not compile.

Distance d1;   // Distance is a class

To make such statements run, the programmer has to explicitly provide a zero argument constructor.

EXAMPLE:

class F
{
int a,b;
public:
F(int x, int y);
void put();
};

F :: F(int x, int y)
{
a=x;
b=y;
}
void F :: put()
{
cout<<”a=”<<a<<endl;
cout<<”b=”<<b;
}
void main()
{
F  obj(5, 9);              //constructor with two arguments will be called
obj.put();
F obj =F(8, 10);
obj.put();
}



No comments:

Post a Comment