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.

#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

Popular Posts

Categories

AI (28) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (121) C (77) C# (12) C++ (82) Course (66) Coursera (184) Cybersecurity (24) data management (11) Data Science (99) Data Strucures (7) Deep Learning (11) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (791) Python Coding Challenge (268) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (41) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses