SlideShare a Scribd company logo
1 of 46
Polymorphism
• The word polymorphism means having many forms.
• The word polymorphism is derived from Greek word
Poly which means many and morphos which means
forms.
• In simple words, we can define polymorphism as the
ability of a message to be displayed in more than one
form.
• A real-life example of polymorphism, a person at the
same time can have different characteristics. Like a
man at the same time is a father, a husband, an
employee.
• So the same person posseses different behavior in
different situations. This is called polymorphism.
• Polymorphism is considered as one of the important
features of Object-Oriented Programming.
Polymorphism
• Refers to ‘one name having many forms’,
‘one interface doing multiple actions’.
• In C++, polymorphism can be either
– static polymorphism or
– dynamic polymorphism.
• C++ implements static polymorphism through
– overloaded functions
– overloaded operators
Polymorphism
• Derived from the Greek - many forms
• Single name can be used for different purposes
• Different ways of achieving the polymorphism:
1. Function overloading
2. Operator overloading
3. Dynamic binding
• Compile time polymorphism: This type of
polymorphism is achieved by function
overloading or operator overloading.
• Function Overloading: When there are
multiple functions with same name but
different parameters then these functions are
said to be overloaded.
• Functions can be overloaded by change in
number of arguments or/and change in
type of arguments.
• Operator Overloading: C++ also provide
option to overload operators.
• For example, we can make the operator (‘+’)
for string class to concatenate two strings.
• We know that this is the addition operator
whose task is to add two operands.
• So a single operator ‘+’ when placed between
integer operands , adds them and when
placed between string operands,
concatenates them.
• Runtime polymorphism: This type of
polymorphism is achieved by Function
Overriding.
• Function overriding on the other hand
occurs when a derived class has a
definition for one of the member functions
of the base class. That base function is
said to be overridden.
Look alike but exhibit different characters
Overloading
• Overloading – A name having two or
more distinct meanings
• Overloaded function - a function having
more than one distinct meanings
• Overloaded operator - When two or more
distinct meanings are defined for an
operator
Overloading
• Operator overloading is inbuilt in C and
C++.
• ‘-’ can be unary as well as binary
• ‘*’ is used for multiplication as well as
pointers
• ‘<<‘, ‘>>’ used as bitwise shift as well as
insertion and extraction operators
• All arithmetic operators can work with any
type of data
Function Overloading
 C++ enables several functions of the same name to be
defined, as long as they have different signatures.
 This is called function overloading.
 The C++ compiler selects the proper function to call by
examining the number, types and order of the
arguments in the call.
 Overloaded functions are distinguished by their signatures
 Signature - Combination of a function’s name and its
parameter types (in order)
 C++ compilers encodes each function identifier with the
number and types of its parameters (sometimes referred to
as name mangling or name decoration) to enable type-safe
linkage.
17
Signature of a Function
• A function’s argument list (i.e., number and
type of argument) is known as the function’s
signature.
• Functions with Same signature - Two
functions with same number and types of
arguments in same order
• variable names doesn’t matter. For
instance, following two functions have
same signature.
void squar (int a, float b); //function 1
void squar (int x, float y);
20
Following code fragment overloads a function
name prnsqr( ).
void prnsqr (int i);
void prnsqr (char c);
void prnsqr (float f);
void prnsqr (double d);
//overloaded for floats #3
//overloaded for double floats #4
//overloaded for character #2
//overloaded for floats #3
//overloaded for integer #1
21
void prnsqr (int i)
{
cout<<“Integer”<<i<<“’s square is”<<i*i<<“n”;
}
void prnsqr (char c);
{
cout <<“No Square for characters”<<“n”;
}
void prnsqr (float f)
{
cout<<“float”<<f <<“’s square is”<<f *f<<“n”;
}
void prnsqr (double d)
{
cout <<“Double float”<<d<<“’s square is”<<d*d<<“n’;
}
using namespace std;
class sample-FO
{
public:
// function with 1 int parameter
void func(int x)
{
cout << "value of x is " << x << endl;
}
void func(double x)
{
cout << "value of x is " << x << endl;
}
void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};
int main() {
sample-FO obj1;
obj1.func(7);
obj1.func(9.132);
obj1.func(85,64);
return 0;
}
Output:
value of x is 7
value of x is 9.132
value of x and y is 85, 64
23
1) Signature of subsequent functions match previous function’s,
then the second is treated as a re-declaration of the first - Error
2) Signatures of two functions match exactly but the return type
differ, then the second declaration is treated as an erroneous
re-declaration of the first
For example,
float square (float f);
double square (float x);
// Differ only by return type so erroneous re-
declaration
//error
Resolution by Compiler when it sees second
function with same name
24
3) If the signature of the two functions differ in
either the number or type of their arguments,
the two functions are considered to be
overloaded.
25
CALLING OVERLOADED FUNCTIONS
Overloaded functions are called just like other
functions. The number and type of arguments
determine which function should be invoked.
For instance consider the following code fragment:
prnsqr (‘z’);
prnsqr (13);
prnsqr (134.520000012);
prnsqr (12.5F);
26
Steps Involved in Finding the Best
Match for a function call
A call to an overloaded function is resolved to a particular
instance of the function, there are three possible cases,
a function call may result in:
a) One match - A match is found for the function call.
b) No match - No match is found for the function call.
c) Ambiguous Match - More than one defined
instance for the function call.
27
1. Exact Match
For example, there are two functions with same name
afunc:
void afunc(int);
void afunc(double);
The function call
afunc(0);
is matched to void afunc(int); and compiler invokes
corresponding function definition
as 0 (zero) is of type int
//overloaded functions
//exactly match. Matches afunc(int)
28
2. A match through promotion
If no exact match is found, an attempt is made to
achieve a match through promotion of the actual
argument.
Recall that the conversion of integer types (char,
short, enumerator, int) into int - integral
promotion.
29
For example, consider the following code
fragment:
void afunc (int);
void afunc (float);
afunc (‘c’);
Will invoke afunc(int)
//match through the promotion;
matches afunc (int)
Compiler resolves
square (‘a’) to
square(int)
Compiler
resolves
square (‘a’) to
square(char)
32
3. A match through application of standard
C++ conversion rules
If no exact match or match through a promotion is
found, an attempt is made to achieve a match
through a standard conversion of the actual
argument. Consider the following example,
void afunc (char);
afunc (471);
//match through standard
conversion matches afunc (char)
33
• ‘int’ argument is converted to char
34
• Error ambiguous call
35
4. A match through application of a user-
defined conversion
• If all the above mentioned steps fail, then the
compiler will try the user-defined conversion in the
combinations to find a unique match.
• Member functions can also be overloaded
36
Default Arguments Versus Overloading
• Using default argument is also overloading,
because the function may be called with an
optional number of arguments.
• For instance, consider the following function
prototype:
float amount (float principal, int time=2,
float rate=0.08);
37
Now this function may be called by providing just one
or two or all three argument values. A function call
like as follows:
cout<<amount (3000);
will invoke the function amount() with argument
values 3000, 2, and 0.08 respectively. Similarly a
function call like
cout <<amount (3000,4);
Will invoke amount() with argument values 3000, 4
and 0.08
cout <<amount (2500,5,0.12);
Will invoke amount() with argument values 2500, 5,
and 0.12 respectively
Finding Gross Pay
• Three are three types of employees in Indian
railways. They are regular, daily wages and
consolidated employees. Gross Pay for the
employees are calculated as follows:
– regular employees - basic + hra + % of DA * basic
– Daily wages – wages per hour * number of hours
– Consolidated – fixed amount
PAC - Finding Gross pay
Input Output Logic Involved
Components for
calculating
gross pay
Gross pay Based on type of
employees –
Calculate gross
pay
Writing Functions
• Same function name for all three type of
employees
• More meaningful and elegant way of doing
things
• I prefer the name - calculate_Gross_Pay for all
types of employees
Case Study Implementation
• Member function search is overloaded
• Railways class has to be friend of train class to
access members of the class
Presentation on polymorphism in c++.pptx
Presentation on polymorphism in c++.pptx

More Related Content

Similar to Presentation on polymorphism in c++.pptx

Similar to Presentation on polymorphism in c++.pptx (20)

oops.pptx
oops.pptxoops.pptx
oops.pptx
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx11.C++Polymorphism [Autosaved].pptx
11.C++Polymorphism [Autosaved].pptx
 
Function Overloading.ppt
Function Overloading.pptFunction Overloading.ppt
Function Overloading.ppt
 
Function in C++
Function in C++Function in C++
Function in C++
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
 
Comparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphismComparison between runtime polymorphism and compile time polymorphism
Comparison between runtime polymorphism and compile time polymorphism
 
polymorphism.pdf
polymorphism.pdfpolymorphism.pdf
polymorphism.pdf
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
Function oveloading
Function oveloadingFunction oveloading
Function oveloading
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
Polymorphism 140527082302-phpapp01
Polymorphism 140527082302-phpapp01Polymorphism 140527082302-phpapp01
Polymorphism 140527082302-phpapp01
 
OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)OOPS & C++(UNIT 4)
OOPS & C++(UNIT 4)
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx21CSC101T best ppt ever OODP UNIT-2.pptx
21CSC101T best ppt ever OODP UNIT-2.pptx
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
Functions
FunctionsFunctions
Functions
 
An Introduction : Python
An Introduction : PythonAn Introduction : Python
An Introduction : Python
 

Recently uploaded

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 

Recently uploaded (20)

Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 

Presentation on polymorphism in c++.pptx

  • 2. • The word polymorphism means having many forms. • The word polymorphism is derived from Greek word Poly which means many and morphos which means forms. • In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. • A real-life example of polymorphism, a person at the same time can have different characteristics. Like a man at the same time is a father, a husband, an employee. • So the same person posseses different behavior in different situations. This is called polymorphism. • Polymorphism is considered as one of the important features of Object-Oriented Programming.
  • 3. Polymorphism • Refers to ‘one name having many forms’, ‘one interface doing multiple actions’. • In C++, polymorphism can be either – static polymorphism or – dynamic polymorphism. • C++ implements static polymorphism through – overloaded functions – overloaded operators
  • 4. Polymorphism • Derived from the Greek - many forms • Single name can be used for different purposes • Different ways of achieving the polymorphism: 1. Function overloading 2. Operator overloading 3. Dynamic binding
  • 5.
  • 6. • Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading. • Function Overloading: When there are multiple functions with same name but different parameters then these functions are said to be overloaded. • Functions can be overloaded by change in number of arguments or/and change in type of arguments.
  • 7. • Operator Overloading: C++ also provide option to overload operators. • For example, we can make the operator (‘+’) for string class to concatenate two strings. • We know that this is the addition operator whose task is to add two operands. • So a single operator ‘+’ when placed between integer operands , adds them and when placed between string operands, concatenates them.
  • 8. • Runtime polymorphism: This type of polymorphism is achieved by Function Overriding. • Function overriding on the other hand occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.
  • 9.
  • 10. Look alike but exhibit different characters
  • 11.
  • 12. Overloading • Overloading – A name having two or more distinct meanings • Overloaded function - a function having more than one distinct meanings • Overloaded operator - When two or more distinct meanings are defined for an operator
  • 13. Overloading • Operator overloading is inbuilt in C and C++. • ‘-’ can be unary as well as binary • ‘*’ is used for multiplication as well as pointers • ‘<<‘, ‘>>’ used as bitwise shift as well as insertion and extraction operators • All arithmetic operators can work with any type of data
  • 14. Function Overloading  C++ enables several functions of the same name to be defined, as long as they have different signatures.  This is called function overloading.  The C++ compiler selects the proper function to call by examining the number, types and order of the arguments in the call.
  • 15.  Overloaded functions are distinguished by their signatures  Signature - Combination of a function’s name and its parameter types (in order)  C++ compilers encodes each function identifier with the number and types of its parameters (sometimes referred to as name mangling or name decoration) to enable type-safe linkage.
  • 16.
  • 17. 17 Signature of a Function • A function’s argument list (i.e., number and type of argument) is known as the function’s signature. • Functions with Same signature - Two functions with same number and types of arguments in same order • variable names doesn’t matter. For instance, following two functions have same signature. void squar (int a, float b); //function 1 void squar (int x, float y);
  • 18.
  • 19.
  • 20. 20 Following code fragment overloads a function name prnsqr( ). void prnsqr (int i); void prnsqr (char c); void prnsqr (float f); void prnsqr (double d); //overloaded for floats #3 //overloaded for double floats #4 //overloaded for character #2 //overloaded for floats #3 //overloaded for integer #1
  • 21. 21 void prnsqr (int i) { cout<<“Integer”<<i<<“’s square is”<<i*i<<“n”; } void prnsqr (char c); { cout <<“No Square for characters”<<“n”; } void prnsqr (float f) { cout<<“float”<<f <<“’s square is”<<f *f<<“n”; } void prnsqr (double d) { cout <<“Double float”<<d<<“’s square is”<<d*d<<“n’; }
  • 22. using namespace std; class sample-FO { public: // function with 1 int parameter void func(int x) { cout << "value of x is " << x << endl; } void func(double x) { cout << "value of x is " << x << endl; } void func(int x, int y) { cout << "value of x and y is " << x << ", " << y << endl; } }; int main() { sample-FO obj1; obj1.func(7); obj1.func(9.132); obj1.func(85,64); return 0; } Output: value of x is 7 value of x is 9.132 value of x and y is 85, 64
  • 23. 23 1) Signature of subsequent functions match previous function’s, then the second is treated as a re-declaration of the first - Error 2) Signatures of two functions match exactly but the return type differ, then the second declaration is treated as an erroneous re-declaration of the first For example, float square (float f); double square (float x); // Differ only by return type so erroneous re- declaration //error Resolution by Compiler when it sees second function with same name
  • 24. 24 3) If the signature of the two functions differ in either the number or type of their arguments, the two functions are considered to be overloaded.
  • 25. 25 CALLING OVERLOADED FUNCTIONS Overloaded functions are called just like other functions. The number and type of arguments determine which function should be invoked. For instance consider the following code fragment: prnsqr (‘z’); prnsqr (13); prnsqr (134.520000012); prnsqr (12.5F);
  • 26. 26 Steps Involved in Finding the Best Match for a function call A call to an overloaded function is resolved to a particular instance of the function, there are three possible cases, a function call may result in: a) One match - A match is found for the function call. b) No match - No match is found for the function call. c) Ambiguous Match - More than one defined instance for the function call.
  • 27. 27 1. Exact Match For example, there are two functions with same name afunc: void afunc(int); void afunc(double); The function call afunc(0); is matched to void afunc(int); and compiler invokes corresponding function definition as 0 (zero) is of type int //overloaded functions //exactly match. Matches afunc(int)
  • 28. 28 2. A match through promotion If no exact match is found, an attempt is made to achieve a match through promotion of the actual argument. Recall that the conversion of integer types (char, short, enumerator, int) into int - integral promotion.
  • 29. 29 For example, consider the following code fragment: void afunc (int); void afunc (float); afunc (‘c’); Will invoke afunc(int) //match through the promotion; matches afunc (int)
  • 32. 32 3. A match through application of standard C++ conversion rules If no exact match or match through a promotion is found, an attempt is made to achieve a match through a standard conversion of the actual argument. Consider the following example, void afunc (char); afunc (471); //match through standard conversion matches afunc (char)
  • 33. 33 • ‘int’ argument is converted to char
  • 35. 35 4. A match through application of a user- defined conversion • If all the above mentioned steps fail, then the compiler will try the user-defined conversion in the combinations to find a unique match. • Member functions can also be overloaded
  • 36. 36 Default Arguments Versus Overloading • Using default argument is also overloading, because the function may be called with an optional number of arguments. • For instance, consider the following function prototype: float amount (float principal, int time=2, float rate=0.08);
  • 37. 37 Now this function may be called by providing just one or two or all three argument values. A function call like as follows: cout<<amount (3000); will invoke the function amount() with argument values 3000, 2, and 0.08 respectively. Similarly a function call like cout <<amount (3000,4); Will invoke amount() with argument values 3000, 4 and 0.08 cout <<amount (2500,5,0.12); Will invoke amount() with argument values 2500, 5, and 0.12 respectively
  • 38. Finding Gross Pay • Three are three types of employees in Indian railways. They are regular, daily wages and consolidated employees. Gross Pay for the employees are calculated as follows: – regular employees - basic + hra + % of DA * basic – Daily wages – wages per hour * number of hours – Consolidated – fixed amount
  • 39. PAC - Finding Gross pay Input Output Logic Involved Components for calculating gross pay Gross pay Based on type of employees – Calculate gross pay
  • 40. Writing Functions • Same function name for all three type of employees • More meaningful and elegant way of doing things • I prefer the name - calculate_Gross_Pay for all types of employees
  • 41.
  • 42.
  • 43.
  • 44. Case Study Implementation • Member function search is overloaded • Railways class has to be friend of train class to access members of the class