Function Overloading
Function Overloading
PROGRAMMING LANGUAGE
2
FUNCTION OVERLOADING
#include <iostream>
using namespace std;
class printData {
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
3
}
};
FUNCTION OVERLOADING
int main(void) {
printData pd;
4
return 0;
}
FUNCTION OVERLOADING
int sum (int x, int y)
{
cout << x+y;
}
7
OVERLOADING CONSTRUCTOR FUNCTIONS
🞆It is possible to overload constructors, but destructors cannot be overloaded
8
OVERLOADING CONSTRUCTOR FUNCTIONS
🞆Overloading constructor functions also allows the programmer to select the
most convenient method to create objects
⚫ Date d1(22, 9, 2007); // uses Date( int d, int m, int y )
⚫ Date d2(“22-Sep-2007”); // uses Date( char* str )
🞆There must be a constructor function for each way that an object of a class will
be created, otherwise compile-time error occurs
🞆Let, we want to write
⚫ MyClass ob1, ob2(10);
🞆Then MyClass should have the following two constructors (it may have more)
⚫ MyClass ( ) { … }
⚫ MyClass ( int n ) { … }
9
🞆Whenever we write a constructor in a class, the compiler does not supply the
default no argument constructor automatically
OVERLOADING CONSTRUCTOR FUNCTIONS
🞆No argument constructor is also necessary for declaring arrays of objects
without any initialization
⚫ MyClass array1[5];
// uses MyClass () { … } for each element
🞆But with the help of an overloaded constructor, we can also initialize the
elements of an array while declaring it
⚫ MyClass array2[3] = {1, 2, 3}
// uses MyClass ( int n ) { … } for each element
🞆As dynamic arrays of objects cannot be initialized, the class must have a no
argument constructor to avoid compiler error while creating dynamic arrays
using “new”. 10
USING DEFAULT ARGUMENTS
🞆 Related to function overloading
⚫ Essentially a shorthand form of function overloading
🞆All default parameters must be to the right of any parameters that don’t have
defaults
⚫ void f2(int a, int b = 0); // no problem
⚫ void f3(int a, int b = 0, int c = 5); // no problem
⚫ void f4(int a = 1, int b); // compiler error
13
OVERLOADING AND AMBIGUITY
🞆Due to automatic type conversion rules
🞆Example 1:
⚫ void f1( float f ) { … }
⚫ void f1( double d ) { … }
⚫ float x = 10.09;
⚫ double y = 10.09;
⚫ f1(x); // unambiguous – use f1(float)
⚫ f1(y); // unambiguous – use f1(double)
⚫ f1(10); // ambiguous, compiler error
🞆Because integer ‘10’ can be promoted to both “float” and “double”.
14
OVERLOADING AND AMBIGUITY
🞆Due to the use of default arguments
🞆Example 3:
⚫ void f3( int a ) { … }
⚫ void f3(int a, int b = 0){…}
⚫ f3(10, 20); // unambiguous – calls f3(int, int)
⚫ f3(10); // ambiguous, compiler error
15