Constructors with argument (Parametrized Constructors)

It's time to see constructors with arguments. They are similar to constructors without arguments. Example is shown below :
class counter
{
private : 
            int count;
public :
    counter (int x) : count (x)
    { }
.................................................// Some other functions in the class
};
int main ( )
{
int y;
counter c1(2);                                                                        
cout<< "What value of count do you want initialise it to?";
cin>>y;
counter c2(y);

......................................
// I'm not typing the rest. It could be anything to suit your purpose.
return 0;

}   

Program is simple. counter c1(2); means that the constructor with one argument is invoked. The argument passed is 2. Its value is assigned to count. count (x) is equal to count = x. Hence count of object c1 is two.

counter c2 (y); means that count of c2 will be initialised to the value of y (i.e. the value the user types in).

Go to the next section : More on Constructors

Or Go to : Contents

Copyright © 2004 Sethu Subramanian All rights reserved.