Friday, 30 March 2018

Constructor with default arguments

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.

class S1
float principle,si,rate_of_int,no_of_yrs;
S1(float p, float n_o_y,float r_o_i=11.5)
void calculate( )
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( );

     Simple INterest is --->4485
     Simple INterest is --->7820
     Simple INterest is --->3660

1 comment:

Popular Posts


Android (21) AngularJS (1) Books (3) C (75) C++ (81) Data Strucures (4) Engineering (13) FPL (17) HTML&CSS (38) IS (25) Java (85) PHP (20) Python (85) R (69) Selenium Webdriver (2) Software (13) SQL (27)