It is possible to define constructor with default arguments.
Default argument must be trailing arguments.
Default argument of the constructor can be overrides by sending the values from calling function.
Let consider
Complex(float real, float imag=0);
The Default value of the argument imag is zero.
The Statement Complex c(2.0);
Will assign 2.0 to real and 0(zero) to imag.
The Statement Complex c(2.0,3.0);
Assigns 2.0 to real and 3.0 to imag.
In Such a way when actual parameters if specified overrides the default values.
Ex:- Declare a class 's1' having data members principle, rate_of_int and no_of_yrs. The constructor will have default values for rate_of_int as 11.5%. Accept the data for two objects and display simple interest for each object.
#include<conio.h>
#include<iostream.h>
class S1
{
float principle,si,rate_of_int,no_of_yrs;
public:
S1(float p, float n_o_y,float r_o_i=11.5)
{
principle=p;
no_of_yrs=n_o_y;
rate_of_int=r_o_i;
}
void calculate( )
{
si=(principle*rate_of_int*no_of_yrs)/100;
}
void display( )
{
cout<<"\n\tSimple INterest is --->"<<si;
}
};
void main( )
{
S1 s1(7800.0f,5.0f);
S1 s2(8500.0f,8.0f);
S1 s3(5000.0f,6,12.2f);
clrscr( );
s1.calculate( );
s2.calculate( );
s3.calculate( );
s1.display( );
s2.display( );
s3.display( );
getch( );
}
Output:-
Simple INterest is --->4485
Simple INterest is --->7820
Simple INterest is --->3660
Default argument must be trailing arguments.
Default argument of the constructor can be overrides by sending the values from calling function.
Let consider
Complex(float real, float imag=0);
The Default value of the argument imag is zero.
The Statement Complex c(2.0);
Will assign 2.0 to real and 0(zero) to imag.
The Statement Complex c(2.0,3.0);
Assigns 2.0 to real and 3.0 to imag.
In Such a way when actual parameters if specified overrides the default values.
Ex:- Declare a class 's1' having data members principle, rate_of_int and no_of_yrs. The constructor will have default values for rate_of_int as 11.5%. Accept the data for two objects and display simple interest for each object.
#include<conio.h>
#include<iostream.h>
class S1
{
float principle,si,rate_of_int,no_of_yrs;
public:
S1(float p, float n_o_y,float r_o_i=11.5)
{
principle=p;
no_of_yrs=n_o_y;
rate_of_int=r_o_i;
}
void calculate( )
{
si=(principle*rate_of_int*no_of_yrs)/100;
}
void display( )
{
cout<<"\n\tSimple INterest is --->"<<si;
}
};
void main( )
{
S1 s1(7800.0f,5.0f);
S1 s2(8500.0f,8.0f);
S1 s3(5000.0f,6,12.2f);
clrscr( );
s1.calculate( );
s2.calculate( );
s3.calculate( );
s1.display( );
s2.display( );
s3.display( );
getch( );
}
Output:-
Simple INterest is --->4485
Simple INterest is --->7820
Simple INterest is --->3660
0 Comments:
Post a Comment