0% found this document useful (0 votes)
6 views2 pages

Polymorphism in CPP

Uploaded by

aditiaggarwalsgi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Polymorphism in CPP

Uploaded by

aditiaggarwalsgi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Polymorphism in C++

■ Polymorphism means 'many forms'. In C++, it allows one function or object to


behave differently depending on the arguments or object type.

1■■ Types of Polymorphism


Type When Decided Achieved By Example
Compile-time At compile time Function / Operator Overloadingadd(int,int) and add(double,double)
Run-time At run time Virtual Functions (Inheritance) Animal -> Dog / Cat

2■■ Example: Compile-time Polymorphism (Function Overloading)


Code:
#include using namespace std; class Math { public: void add(int a, int b) { cout <<
"Sum of integers: " << a + b << endl; } void add(double a, double b) { cout << "Sum
of doubles: " << a + b << endl; } void add(int a, int b, int c) { cout << "Sum of three
integers: " << a + b + c << endl; } }; int main() { Math obj; [Link](5, 10);
[Link](2.5, 3.7); [Link](1, 2, 3); return 0; }

■ Step-by-Step Explanation:
1. The class Math contains three 'add()' functions with different parameter lists
(function overloading).
2. The compiler decides which function to call based on the number and type of
arguments.
3. [Link](5,10) calls add(int,int).
4. [Link](2.5,3.7) calls add(double,double).
5. [Link](1,2,3) calls add(int,int,int).

■ Output:
Sum of integers: 15 Sum of doubles: 6.2 Sum of three integers: 6

■ Diagram: How Compiler Selects the Right Function


[Link](...) | ----------------------------- | | | add(int,int) add(double,double)
add(int,int,int) | | | 5,10 2.5,3.7 1,2,3 | | | Sum of integers Sum of doubles Sum of
three integers

■ Key Points:
• Function overloading enables multiple functions with the same name but different
parameters.
• The compiler selects the correct function at compile time (Compile-time
Polymorphism).
• Helps make code clean, readable, and reusable.

You might also like