Object-Oriented Programming In C++: Overloading and Default Arguments
Submitted by PhoeniciansSy on Tuesday, September 9, 2014 - 21:36.
Content:
1. Function overloading in C++. 2. Default arguments in c++.Function Overloading in C++:
We can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. We can not overload function declarations that differ only by return type. Example: We can define a function called display to print a integer number. but the number may double too, and we do not have to define a function with another name, we can overload this function as following:- void display (int i )
- {
- cout<<"integer "<<i<<endl;
- }
- void display (double i )
- {
- cout<<"double " <<i<<endl;
- }
- int main( )
- {
- display(7);
- display(3.5);
- return 0;
- }
integer 7 double 3.5
Default Arguments in C++:
When the programmer write a function with arguments, may some of those arguments can have values which are known in advance. In this case we can write a function with default arguments. Using default arguments makes the calling of the function faster because there is no need to copy them. Example:- void init (inta ,intb = 0) ; // 2'nd argument = 0 by default
- init (3); init (2,4);
void incorrect(int a =3,int b,int c= 0) ; // error , b has no value
If we write the default arguments in the prototype of a function, we can not rewrite this arguments with their values in the definition.
- void init (int a = 0) ; // declaration of init
- void init (int a = 0) {/* body */ } //definition of init ERROR
- void init (int a = 0) ;// declaration of init
- void init (int a ){ / * body * / } //OK
- #include <iostream>
- void init(int,int=3);
- void init(int a,int b)
- {
- cout<<a <<","<<b;
- }
- void init(int=7,int); // overdefinition
- int main()
- {
- init(2,1); // displays 2,1
- init(4); // displays 4,3
- init(); // displays 7,3
- return 0;
- }
Add new comment
- 77 views