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

100 Python Programs for Beginner (53) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (358) Python Quiz (23) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

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