C++ multiple constructor in a class
so far we have used two kinds of constructor. They are
integer();
integer(int,int)
In the first case, the constructor integer() itself supplies the data values and no values are passed by the calling program.
in above example, In the second case the function call passes the appropriate values from main(). C++ permits use to both these constructors in the same class.
For example in the below we could define a class as follows
class integer
{
m,n;
:
integer()
{
m=0;
n=0;
}
integer( a, b)
{
m=a;
n=b;
}
integer(integer &i)
{
m=i.m;
n=i.n;
}
};
|
This declares three constructor for an integer object.so The first constructor receives no arguments, and The second case receive two integer arguments and the third receives one integer object as an argument. for example The Declaration
would automatically invoke first constructor and set both m and n of I1 to zero.
The statement
would call the second constructor which will initialize the data members m , n of I2 to 20 and 0 respectively.
Finally the statement
integer I3(I2);
would invoked
|
CONTSRUCTOR WITH DEFAULT ARGUMENTS
iT IS possible to define constructor with default arguments for example, The constructor complex() can be declared as follows
complex(float real,float img=0);
|
The default value of the argument img is zero. Then the statement
assign the value 5.0 to real variable and 0.0 to img(by default) however the statement
assigns 2.0 real and 3.0 to img. The actual parameter(arguments), when specified overrides the default value as pointed out earlier, The missing arguments must be the trailing ones it is important to difference between the default constructor A::A() and the default arguments constructor
A:A()(int=0).
The default argument constructor can be called with either no arguments or one argument. When called with no arguments, it becomes a default constructor.
When both those forms are used in a class, it generates ambiguity for statement such as
A a;
The ambiguity is whether to call A::A() or A:A(int=0)