Object-Oriented Programming In C++: Overloading and Default Arguments

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:
  1. void display (int i )
  2. {
  3. cout<<"integer "<<i<<endl;
  4. }
  5. void display (double i )
  6. {
  7. cout<<"double " <<i<<endl;
  8. }
  9. int main( )
  10. {
  11. display(7);
  12. display(3.5);
  13. return 0;
  14. }
the output:
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:
  1. void init (inta ,intb = 0) ; // 2'nd argument = 0 by default
  2. init (3); init (2,4);
We must put the default arguments in the right side of others arguments: 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.
  1. void init (int a = 0) ; // declaration of init
  2. void init (int a = 0) {/* body */ } //definition of init ERROR
  1. void init (int a = 0) ;// declaration of init
  2. void init (int a ){ / * body * / } //OK
Full Example:
  1. #include <iostream>
  2. void init(int,int=3);
  3. void init(int a,int b)
  4. {
  5. cout<<a <<","<<b;
  6. }
  7. void init(int=7,int); // overdefinition
  8. int main()
  9. {
  10. init(2,1); // displays 2,1
  11. init(4); // displays 4,3
  12. init(); // displays 7,3
  13. return 0;
  14. }

Tags

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
10 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.