SlideShare a Scribd company logo
1 of 21
Download to read offline
Polymorphism
By,
Riya Wagh
Under the Guidance of,
Dr . Rachna Navalakhe
➢ The word “polymorphism”means having many forms.
➢ The term "Polymorphism" is the combination of "poly" + "morphs" which means
many forms. It is a greek word.
Let's consider a real-life example of
polymorphism. A lady behaves like
a teacher in a classroom, mother or daughter
in a home and customer in a market. Here, a
single person is behaving differently according
to the situations.
Compile-Time Polymorphism
FUNCTION OVERLOADING OPERATOR OVERLOADING.
A. Function
Overloading
• When there are multiple functions with the same name
but different parameters, then the functions are said to
be overloaded, hence this is known as Function
Overloading. Functions can be overloaded by changing
the number of arguments or/and changing the
type of arguments.
// C++ program to demonstrate
// function overloading or
// Compile-time Polymorphism
#include <bits/stdc++.h>
using namespace std;
class Geeks {
public:
// Function with 1 int parameter
void func(int x)
{
cout << "value of x is " <<
x << endl;
}
// Function with same name but
// 1 double parameter
void func(double x)
{
cout << "value of x is " <<
x << endl;
}
// Function with same name and
// 2 int parameters
void func(int x, int y)
{
cout << "value of x and y is " <<
x << ", " << y << endl;
}
};
// Driver code
int main()
{
Geeks obj1;
// Function being called depends
// on the parameters passed
// func() is called with int value
obj1.func(7);
// func() is called with double value
obj1.func(9.132);
// func() is called with 2 int values
obj1.func(85, 64);
return 0;
}
Explanation: In the above example, a
single function named
function func() acts differently in
three different situations, which is a
property of polymorphism.
Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64
B. Operator
Overloading
• C++ has the ability to provide the operators with a
special meaning for a data type, this ability is known as
operator overloading. For example, we can make use of
the addition operator (+) for string class to concatenate
two strings. We know that the task of this operator is to
add two operands. So a single operator ‘+’, when placed
between integer operands, adds them and when placed
between string operands, concatenates them.
// C++ program to demonstrate
// Operator Overloading or
// Compile-Time Polymorphism
#include <iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0,
int i = 0)
{
real = r;
imag = i;
}
// This is automatically called
// when '+' is used with between
// two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print()
{
cout << real << " + i" <<
imag << endl;
}
};
// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);
// An example call to "operator+"
Complex c3 = c1 + c2;
c3.print();
}
Output
12 + i9
• Explanation: In the above example, the
operator ‘+’ is overloaded. Usually, this
operator is used to add two numbers
(integers or floating point numbers), but here
the operator is made to perform the addition
of two imaginary or complex numbers.
Runtime
Polymorphism
• Run time polymorphism is achieved when the object's
method is invoked at the run time instead of compile
time. It is achieved by method overriding which is also
known as dynamic binding or late binding.
virtual function
1
A C++ virtual function is a
member function in the
base class that you redefine
in a derived class. It is
declared using the virtual
keyword.
2
It is used to tell the
compiler to perform
dynamic linkage or late
binding on the function.
3
There is a necessity to use
the single pointer to refer
to all the objects of the
different classes. So, we
create the pointer to the
base class that refers to all
the derived objects. But,
when base class pointer
contains the address of the
derived class object, always
executes the base class
function. This issue can only
be resolved by using the
'virtual' function.
4
A 'virtual' is a keyword
preceding the normal
declaration of a function.
5
When the function is made
virtual, C++ determines
which function is to be
invoked at the runtime
based on the type of the
object pointed by the base
class pointer.
Late binding or Dynamic
linkage
• In late binding function call is resolved during runtime.
Therefore compiler determines the type of object at
runtime, and then binds the function call.
Rules of Virtual Function
Virtualfunctions must be members of some
class.
Virtualfunctions cannot be static members.
They are accessed through object pointers.
They can be a friend of another class.
A virtualfunction must be defined in the base
class, even though it is not used.
The prototypes of a virtualfunction of the base
class and allthe derived classes must be
identical.If the two functions with the same
name but different prototypes,C++ will
consider them as the overloaded functions.
We cannot have a virtualconstructor,but we
can have a virtualdestructor
Consider the situation when we don't use the
virtualkeyword.
#include <iostream>
using namespace std;
class A
{
int x=5;
public:
void display()
{
std::cout << "Value of x is : " << x<<std::endl;
}
};
class B: public A
{
int y = 10;
public:
void display()
{
std::cout << "Value of y is : " <<y<< std::endl;
}
};
int main()
{
A *a;
B b;
a = &b;
a->display();
return 0;
}
Output:
Value of x is : 5
• * a is the base class pointer. The pointer
can only access the base class members but
not the members of the derived class.
Although C++ permits the base pointer to
point to any object derived from the base
class, it cannot directly access the members
of the derived class. Therefore, there is a
need for virtual function which allows the
base pointer to access the members of the
derived class.
Compile time polymorphism Run time polymorphism
The function to be invoked is known at the compile time. The function to be invoked is known at the run time.
It is also known as overloading, early binding and static binding. It is also known as overriding, Dynamic binding and late binding.
Overloading is a compile time polymorphism where more than
one method is having the same name but with the different
number of parameters or the type of the parameters.
Overriding is a run time polymorphism where more than one
method is having the same name, number of parameters and the
type of the parameters.
It is achieved by function overloading and operator overloading. It is achieved by virtual functions and pointers.
It provides fast execution as it is known at the compile time. It provides slow execution as it is known at the run time.
It is less flexible as mainly all the things execute at the compile
time.
It is more flexible as all the things execute at the run time.
polymorphism.pdf

More Related Content

Similar to polymorphism.pdf

polymorphism and virtual function
polymorphism and virtual functionpolymorphism and virtual function
polymorphism and virtual functionBhanuprataparya
 
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 polymorphismCHAITALIUKE1
 
C++ concept of Polymorphism
C++ concept of  PolymorphismC++ concept of  Polymorphism
C++ concept of Polymorphismkiran Patel
 
Polymorphism
PolymorphismPolymorphism
PolymorphismAmir Ali
 
Polymorphism and its types
Polymorphism and its typesPolymorphism and its types
Polymorphism and its typesSuraj Bora
 
Presentation on polymorphism in c++.pptx
Presentation on polymorphism in c++.pptxPresentation on polymorphism in c++.pptx
Presentation on polymorphism in c++.pptxvishwadeep15
 
Polymorphism
PolymorphismPolymorphism
Polymorphismzindadili
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptxrayanbabur
 
Polymorphism 140527082302-phpapp01
Polymorphism 140527082302-phpapp01Polymorphism 140527082302-phpapp01
Polymorphism 140527082302-phpapp01Engr.Tazeen Ahmed
 
Oopsecondgrouppresentation 180726073512-converted (1)
Oopsecondgrouppresentation 180726073512-converted (1)Oopsecondgrouppresentation 180726073512-converted (1)
Oopsecondgrouppresentation 180726073512-converted (1)Hassan Hashmi
 
polymorphism-17013114666666666653806.pdf
polymorphism-17013114666666666653806.pdfpolymorphism-17013114666666666653806.pdf
polymorphism-17013114666666666653806.pdfkashafishfaq21
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
C questions
C questionsC questions
C questionsparm112
 

Similar to polymorphism.pdf (20)

polymorphism and virtual function
polymorphism and virtual functionpolymorphism and virtual function
polymorphism and virtual function
 
C++ first s lide
C++ first s lideC++ first s lide
C++ first s lide
 
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
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
C++ concept of Polymorphism
C++ concept of  PolymorphismC++ concept of  Polymorphism
C++ concept of Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
Polymorphism and its types
Polymorphism and its typesPolymorphism and its types
Polymorphism and its types
 
Presentation on polymorphism in c++.pptx
Presentation on polymorphism in c++.pptxPresentation on polymorphism in c++.pptx
Presentation on polymorphism in c++.pptx
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
full defination of final opp.pptx
full defination of final opp.pptxfull defination of final opp.pptx
full defination of final opp.pptx
 
Polymorphism 140527082302-phpapp01
Polymorphism 140527082302-phpapp01Polymorphism 140527082302-phpapp01
Polymorphism 140527082302-phpapp01
 
Oopsecondgrouppresentation 180726073512-converted (1)
Oopsecondgrouppresentation 180726073512-converted (1)Oopsecondgrouppresentation 180726073512-converted (1)
Oopsecondgrouppresentation 180726073512-converted (1)
 
polymorphism-17013114666666666653806.pdf
polymorphism-17013114666666666653806.pdfpolymorphism-17013114666666666653806.pdf
polymorphism-17013114666666666653806.pdf
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
OOP_UnitIII.pdf
OOP_UnitIII.pdfOOP_UnitIII.pdf
OOP_UnitIII.pdf
 
oops.pptx
oops.pptxoops.pptx
oops.pptx
 
C questions
C questionsC questions
C questions
 

Recently uploaded

Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |aasikanpl
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRlizamodels9
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxLIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxmalonesandreagweneth
 
Call Girls in Hauz Khas Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Hauz Khas Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Hauz Khas Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Hauz Khas Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.PraveenaKalaiselvan1
 
Solution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutionsSolution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutionsHajira Mahmood
 
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
TOPIC 8 Temperature and Heat.pdf physics
TOPIC 8 Temperature and Heat.pdf physicsTOPIC 8 Temperature and Heat.pdf physics
TOPIC 8 Temperature and Heat.pdf physicsssuserddc89b
 
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSpermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSarthak Sekhar Mondal
 
Artificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PArtificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PPRINCE C P
 
Cytokinin, mechanism and its application.pptx
Cytokinin, mechanism and its application.pptxCytokinin, mechanism and its application.pptx
Cytokinin, mechanism and its application.pptxVarshiniMK
 
TOTAL CHOLESTEROL (lipid profile test).pptx
TOTAL CHOLESTEROL (lipid profile test).pptxTOTAL CHOLESTEROL (lipid profile test).pptx
TOTAL CHOLESTEROL (lipid profile test).pptxdharshini369nike
 
zoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistanzoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistanzohaibmir069
 
Heredity: Inheritance and Variation of Traits
Heredity: Inheritance and Variation of TraitsHeredity: Inheritance and Variation of Traits
Heredity: Inheritance and Variation of TraitsCharlene Llagas
 
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxNandakishor Bhaurao Deshmukh
 
Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫qfactory1
 
insect anatomy and insect body wall and their physiology
insect anatomy and insect body wall and their  physiologyinsect anatomy and insect body wall and their  physiology
insect anatomy and insect body wall and their physiologyDrAnita Sharma
 
Speech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxSpeech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxpriyankatabhane
 

Recently uploaded (20)

Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Lajpat Nagar (Delhi) |
 
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCRCall Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
Call Girls In Nihal Vihar Delhi ❤️8860477959 Looking Escorts In 24/7 Delhi NCR
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptxLIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
LIGHT-PHENOMENA-BY-CABUALDIONALDOPANOGANCADIENTE-CONDEZA (1).pptx
 
Call Girls in Hauz Khas Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Hauz Khas Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Hauz Khas Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Hauz Khas Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
BIOETHICS IN RECOMBINANT DNA TECHNOLOGY.
 
Solution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutionsSolution chemistry, Moral and Normal solutions
Solution chemistry, Moral and Normal solutions
 
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
TOPIC 8 Temperature and Heat.pdf physics
TOPIC 8 Temperature and Heat.pdf physicsTOPIC 8 Temperature and Heat.pdf physics
TOPIC 8 Temperature and Heat.pdf physics
 
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSpermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
 
Artificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PArtificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C P
 
Cytokinin, mechanism and its application.pptx
Cytokinin, mechanism and its application.pptxCytokinin, mechanism and its application.pptx
Cytokinin, mechanism and its application.pptx
 
TOTAL CHOLESTEROL (lipid profile test).pptx
TOTAL CHOLESTEROL (lipid profile test).pptxTOTAL CHOLESTEROL (lipid profile test).pptx
TOTAL CHOLESTEROL (lipid profile test).pptx
 
zoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistanzoogeography of pakistan.pptx fauna of Pakistan
zoogeography of pakistan.pptx fauna of Pakistan
 
Heredity: Inheritance and Variation of Traits
Heredity: Inheritance and Variation of TraitsHeredity: Inheritance and Variation of Traits
Heredity: Inheritance and Variation of Traits
 
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
 
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptxTHE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
THE ROLE OF PHARMACOGNOSY IN TRADITIONAL AND MODERN SYSTEM OF MEDICINE.pptx
 
Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫Manassas R - Parkside Middle School 🌎🏫
Manassas R - Parkside Middle School 🌎🏫
 
insect anatomy and insect body wall and their physiology
insect anatomy and insect body wall and their  physiologyinsect anatomy and insect body wall and their  physiology
insect anatomy and insect body wall and their physiology
 
Speech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptxSpeech, hearing, noise, intelligibility.pptx
Speech, hearing, noise, intelligibility.pptx
 

polymorphism.pdf

  • 1. Polymorphism By, Riya Wagh Under the Guidance of, Dr . Rachna Navalakhe
  • 2. ➢ The word “polymorphism”means having many forms. ➢ The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a greek word. Let's consider a real-life example of polymorphism. A lady behaves like a teacher in a classroom, mother or daughter in a home and customer in a market. Here, a single person is behaving differently according to the situations.
  • 3.
  • 5. A. Function Overloading • When there are multiple functions with the same name but different parameters, then the functions are said to be overloaded, hence this is known as Function Overloading. Functions can be overloaded by changing the number of arguments or/and changing the type of arguments.
  • 6. // C++ program to demonstrate // function overloading or // Compile-time Polymorphism #include <bits/stdc++.h> using namespace std; class Geeks { public: // Function with 1 int parameter void func(int x) { cout << "value of x is " << x << endl; } // Function with same name but // 1 double parameter void func(double x) { cout << "value of x is " << x << endl; }
  • 7. // Function with same name and // 2 int parameters void func(int x, int y) { cout << "value of x and y is " << x << ", " << y << endl; } }; // Driver code int main() { Geeks obj1; // Function being called depends // on the parameters passed // func() is called with int value obj1.func(7); // func() is called with double value obj1.func(9.132); // func() is called with 2 int values obj1.func(85, 64); return 0; }
  • 8. Explanation: In the above example, a single function named function func() acts differently in three different situations, which is a property of polymorphism. Output value of x is 7 value of x is 9.132 value of x and y is 85, 64
  • 9. B. Operator Overloading • C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can make use of the addition operator (+) for string class to concatenate two strings. We know that the task of this operator is to add two operands. So a single operator ‘+’, when placed between integer operands, adds them and when placed between string operands, concatenates them.
  • 10. // C++ program to demonstrate // Operator Overloading or // Compile-Time Polymorphism #include <iostream> using namespace std; class Complex { private: int real, imag; public: Complex(int r = 0, int i = 0) { real = r; imag = i; } // This is automatically called // when '+' is used with between // two Complex objects
  • 11. Complex operator+(Complex const& obj) { Complex res; res.real = real + obj.real; res.imag = imag + obj.imag; return res; } void print() { cout << real << " + i" << imag << endl; } }; // Driver code int main() { Complex c1(10, 5), c2(2, 4); // An example call to "operator+" Complex c3 = c1 + c2; c3.print(); }
  • 12. Output 12 + i9 • Explanation: In the above example, the operator ‘+’ is overloaded. Usually, this operator is used to add two numbers (integers or floating point numbers), but here the operator is made to perform the addition of two imaginary or complex numbers.
  • 13. Runtime Polymorphism • Run time polymorphism is achieved when the object's method is invoked at the run time instead of compile time. It is achieved by method overriding which is also known as dynamic binding or late binding.
  • 14. virtual function 1 A C++ virtual function is a member function in the base class that you redefine in a derived class. It is declared using the virtual keyword. 2 It is used to tell the compiler to perform dynamic linkage or late binding on the function. 3 There is a necessity to use the single pointer to refer to all the objects of the different classes. So, we create the pointer to the base class that refers to all the derived objects. But, when base class pointer contains the address of the derived class object, always executes the base class function. This issue can only be resolved by using the 'virtual' function. 4 A 'virtual' is a keyword preceding the normal declaration of a function. 5 When the function is made virtual, C++ determines which function is to be invoked at the runtime based on the type of the object pointed by the base class pointer.
  • 15. Late binding or Dynamic linkage • In late binding function call is resolved during runtime. Therefore compiler determines the type of object at runtime, and then binds the function call.
  • 16. Rules of Virtual Function Virtualfunctions must be members of some class. Virtualfunctions cannot be static members. They are accessed through object pointers. They can be a friend of another class. A virtualfunction must be defined in the base class, even though it is not used. The prototypes of a virtualfunction of the base class and allthe derived classes must be identical.If the two functions with the same name but different prototypes,C++ will consider them as the overloaded functions. We cannot have a virtualconstructor,but we can have a virtualdestructor Consider the situation when we don't use the virtualkeyword.
  • 17. #include <iostream> using namespace std; class A { int x=5; public: void display() { std::cout << "Value of x is : " << x<<std::endl; } }; class B: public A { int y = 10; public: void display() { std::cout << "Value of y is : " <<y<< std::endl; } };
  • 18. int main() { A *a; B b; a = &b; a->display(); return 0; } Output: Value of x is : 5
  • 19. • * a is the base class pointer. The pointer can only access the base class members but not the members of the derived class. Although C++ permits the base pointer to point to any object derived from the base class, it cannot directly access the members of the derived class. Therefore, there is a need for virtual function which allows the base pointer to access the members of the derived class.
  • 20. Compile time polymorphism Run time polymorphism The function to be invoked is known at the compile time. The function to be invoked is known at the run time. It is also known as overloading, early binding and static binding. It is also known as overriding, Dynamic binding and late binding. Overloading is a compile time polymorphism where more than one method is having the same name but with the different number of parameters or the type of the parameters. Overriding is a run time polymorphism where more than one method is having the same name, number of parameters and the type of the parameters. It is achieved by function overloading and operator overloading. It is achieved by virtual functions and pointers. It provides fast execution as it is known at the compile time. It provides slow execution as it is known at the run time. It is less flexible as mainly all the things execute at the compile time. It is more flexible as all the things execute at the run time.