C++
Polymorphism
• What is polymorphism
• Compile and run time
• Compile time
1. Function Overloading p:2
2. operator overloading p:1
• Run time
1. Function overriding p: 2
2. Virtual function p:2
Polymorphism
• The term "Polymorphism" is the combination of
"poly" + "morphs" which means many forms. It is
a greek word. In object-oriented programming,
we use 3 main concepts: inheritance,
encapsulation, and polymorphism.
• Real Life Example Of Polymorphism
• 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 n run time
• Compile-time is the time at which the source
code is converted into an executable code
• while the run time is the time at which the
executable code is started running.
• Both the compile-time and runtime refer to
different types of error.
• Compile time polymorphism: The overloaded
functions are invoked by matching the type
and number of arguments.
• This information is available at the compile
time and, therefore, compiler selects the
appropriate function at the compile time.
• It is achieved by function overloading and
operator overloading which is also known as
static binding or early binding.
• Now, let's consider the case where function
name and prototype is same.
•
• 1. overloading program
• here derived class get executed
• In function overloading, there are many
functions with similar names but different
arguments.
• The parameters can differ in number or type.
1.Program
• class A // base class declaration.
• {
• int a;
• public:
• void display()
• {
• cout<< "Class A ";
• }
• };
• class B : public A // derived class dec
laration.
• {
• int b;
• public:
• void display()
• {
• cout<<"Class B";
• }
• }; op: Class B
Explanation 1.
• In the above case, the prototype of display()
function is the same in both the base and
derived class.
• Therefore, the static binding cannot be
applied.
• It would be great if the appropriate function is
selected at the run time. This is known as run
time polymorphism.
2.
• 2. each function get identify according to their
parameters
• 2.Program
• 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;
• }
• };
int main() {
Geeks obj1;
// Which function is called will depend on the parameters
passed
// The first 'func' is called
obj1.func(7);
// The second 'func' is called
obj1.func(9.132);
// The third 'func' is called
obj1.func(85,64);
return 0;
}
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.
Operator Overloading
• In Operator Overloading, we define a new
meaning for a C++ operator. It also changes how
the operator works.
• For example, we can define the + operator to
concatenate two strings. We know it as the
addition operator for adding numerical values.
After our definition, when placed between
integers, it will add them.
• When placed between strings, it will concatenate
them.
• C++ Operators Overloading
• Operator overloading is a compile-time polymorphism in
which the operator is overloaded to provide the special
meaning to the user-defined data type. Operator
overloading is used to overload or redefines most of the
operators available in C++. It is used to perform the
operation on the user-defined data type. For example, C++
provides the ability to add the variables of the user-defined
data type that is applied to the built-in data types.
• The advantage of Operators overloading is to perform
different operations on the same operand.
• Operator that cannot be overloaded are as follows:
• Scope operator (::)
• Sizeof
• member selector(.)
• member pointer selector(*)
• ternary operator(?:)
• Syntax of Operator Overloading
• return_type class_name : : operator op(argument_list)
• {
• // body of the function.
• }
• Where the return type is the type of value returned by the
function.
• class_name is the name of the class.
• operator op is an operator function where op is the
operator being overloaded, and the operator is the
keyword.
• Rules for Operator Overloading
• Existing operators can only be overloaded, but the new operators
cannot be overloaded.
• The overloaded operator contains atleast one operand of the user-
defined data type.
• We cannot use friend function to overload certain operators.
However, the member function can be used to overload those
operators.
• When unary operators are overloaded through a member function
take no explicit arguments, but, if they are overloaded by a friend
function, takes one argument.
• When binary operators are overloaded through a member function
takes one explicit argument, and if they are overloaded through a
friend function takes two explicit arguments.
3.Program
• Operator overloading
• class ComplexNum {
• private:
• int real, over;
• public:
• ComplexNum(int rl = 0, int ov = 0) {
• real = rl;
• over = ov;
• }
• ComplexNum operator + (ComplexNum const &obj) {
• ComplexNum result;
• result.real = real + obj.real;
• result.over = over + obj.over;
• return result;
• }
• void print() {
• cout << real << " + i" << over << endl;
• }
• };
• int main()
• {
• ComplexNum c1(10, 2), c2(3, 7);
• ComplexNum c3 = c1+c2;
• c3.print();
• }13+i9
Run time polymorphism
• Run time 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.
• Function Overriding
• Function overriding occurs when a function of
the base class is given a new definition in a
derived class. At that time, we can say the
base function has been overridden.
• For example:
4. Program
• Function Overriding
• class Mammal {
• public:
• void eat() {
• cout << "Mammals eat...";
• }};
• class Cow: public Mammal {
• public:
• void eat() {
• cout << "Cows eat grass...";
• }};
• int main(void) {
• Cow c = Cow();
• c.eat();
• return 0;}
• O p:Cows eat grass utput:
5.program
• C++ Runtime Polymorphism Example
• // an example without the virtual keyword.
5.program
class Animal {
• public:
• void eat(){
• cout<<"Eating...";
• }
• };
• class Dog: public Animal
• {
• public:
• void eat()
• { cout<<"Eating bread...";
• }
• };
• int main(void) {
• Dog d = Dog();
• d.eat();
• return 0;
• }
• op:eating bread
Runtime Polymorphism with Data
Members
• Runtime Polymorphism can be achieved by
data members in C++. Let's see an example
where we are accessing the field by reference
variable which refers to the instance of
derived class.
•
1.#include <iostream>
2.using namespace std;
3.class Animal { // base class declaration.
4. public:
5. string color = "Black";
6.};
7.class Dog: public Animal // inheriting Animal class.
8.{
9. public:
10. string color = "Grey";
11.};
12.int main(void) {
13. Animal d= Dog();
14. cout<<d.color;
15.}
Output:
Black
Virtual Function in C++
• A virtual function is a member function which is
declared within a base class and is re-
defined(Overriden) by a derived class.
• When you refer to a derived class object using a
pointer or a reference to the base class,
• you can call a virtual function for that object and
execute the derived class’s version of the
function.
•
Rules for Virtual Functions
• Virtual functions cannot be static.
• A virtual function can be a friend function of another class.
• Virtual functions should be accessed using pointer or
reference of base class type to achieve run time
polymorphism.
• The prototype of virtual functions should be the same in
the base as well as derived class.
• They are always defined in the base class and overridden in
a derived class. It is not mandatory for the derived class to
override (or re-define the virtual function), in that case, the
base class version of the function is used.
• A class may have virtual destructor but it cannot have a
virtual constructor.
• class A
• {
• public:
• void display()
• { int x=5;
• cout << "Value of x is : " << x;
• }
• };
• class B: public A
• { public:
• void display()
• { int y = 10;
• cout << "Value of y is : " <<y;
• }
• };
• int main()
• {
• A *a; //base class
• B b; //derived
• a = &b;
• a->display();
• return 0;
• }
• Output:
• Value of x is : 5
• In the above example, * 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
• C++ virtual function Example
• Let's see the simple example of C++ virtual function used to invoked
the derived class in a program.
• #include <iostream>
• {
• public:
• virtual void display()
• {
• cout << "Base class is invoked"<<endl;
• }
• };
• class B:public A
• {
• public:
• void display()
• {
• cout << "Derived Class is invoked"<<endl;
• }
• };
• int main()
• {
• A* a; //pointer of base class
• B b; //object of derived class
• a = &b;
• a->display(); //Late Binding occurs
• }
• Output:
• Derived Class is invoked
• Or

11.C++Polymorphism [Autosaved].pptx

  • 1.
  • 2.
  • 3.
    • What ispolymorphism • Compile and run time • Compile time 1. Function Overloading p:2 2. operator overloading p:1 • Run time 1. Function overriding p: 2 2. Virtual function p:2
  • 4.
    Polymorphism • The term"Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a greek word. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation, and polymorphism. • Real Life Example Of Polymorphism • 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.
  • 6.
    Compile n runtime • Compile-time is the time at which the source code is converted into an executable code • while the run time is the time at which the executable code is started running. • Both the compile-time and runtime refer to different types of error.
  • 7.
    • Compile timepolymorphism: The overloaded functions are invoked by matching the type and number of arguments. • This information is available at the compile time and, therefore, compiler selects the appropriate function at the compile time. • It is achieved by function overloading and operator overloading which is also known as static binding or early binding. • Now, let's consider the case where function name and prototype is same. •
  • 8.
    • 1. overloadingprogram • here derived class get executed • In function overloading, there are many functions with similar names but different arguments. • The parameters can differ in number or type.
  • 9.
    1.Program • class A// base class declaration. • { • int a; • public: • void display() • { • cout<< "Class A "; • } • };
  • 10.
    • class B: public A // derived class dec laration. • { • int b; • public: • void display() • { • cout<<"Class B"; • } • }; op: Class B
  • 11.
    Explanation 1. • Inthe above case, the prototype of display() function is the same in both the base and derived class. • Therefore, the static binding cannot be applied. • It would be great if the appropriate function is selected at the run time. This is known as run time polymorphism.
  • 12.
    2. • 2. eachfunction get identify according to their parameters
  • 13.
    • 2.Program • classGeeks • { • public: • • // function with 1 int parameter • void func(int x) • { • cout << "value of x is " << x << endl; • } • •
  • 14.
    • // functionwith 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; • } • };
  • 15.
    int main() { Geeksobj1; // Which function is called will depend on the parameters passed // The first 'func' is called obj1.func(7); // The second 'func' is called obj1.func(9.132); // The third 'func' is called obj1.func(85,64); return 0; }
  • 16.
    Compile time polymorphismRun 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.
  • 17.
    Operator Overloading • InOperator Overloading, we define a new meaning for a C++ operator. It also changes how the operator works. • For example, we can define the + operator to concatenate two strings. We know it as the addition operator for adding numerical values. After our definition, when placed between integers, it will add them. • When placed between strings, it will concatenate them.
  • 18.
    • C++ OperatorsOverloading • Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type. For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types. • The advantage of Operators overloading is to perform different operations on the same operand. • Operator that cannot be overloaded are as follows: • Scope operator (::) • Sizeof • member selector(.) • member pointer selector(*) • ternary operator(?:)
  • 19.
    • Syntax ofOperator Overloading • return_type class_name : : operator op(argument_list) • { • // body of the function. • } • Where the return type is the type of value returned by the function. • class_name is the name of the class. • operator op is an operator function where op is the operator being overloaded, and the operator is the keyword.
  • 20.
    • Rules forOperator Overloading • Existing operators can only be overloaded, but the new operators cannot be overloaded. • The overloaded operator contains atleast one operand of the user- defined data type. • We cannot use friend function to overload certain operators. However, the member function can be used to overload those operators. • When unary operators are overloaded through a member function take no explicit arguments, but, if they are overloaded by a friend function, takes one argument. • When binary operators are overloaded through a member function takes one explicit argument, and if they are overloaded through a friend function takes two explicit arguments.
  • 21.
  • 22.
    • class ComplexNum{ • private: • int real, over; • public: • ComplexNum(int rl = 0, int ov = 0) { • real = rl; • over = ov; • } • ComplexNum operator + (ComplexNum const &obj) { • ComplexNum result; • result.real = real + obj.real; • result.over = over + obj.over; • return result; • }
  • 23.
    • void print(){ • cout << real << " + i" << over << endl; • } • }; • int main() • { • ComplexNum c1(10, 2), c2(3, 7); • ComplexNum c3 = c1+c2; • c3.print(); • }13+i9
  • 24.
  • 25.
    • Run timepolymorphism: 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.
  • 26.
    • Function Overriding •Function overriding occurs when a function of the base class is given a new definition in a derived class. At that time, we can say the base function has been overridden. • For example:
  • 27.
  • 28.
    • class Mammal{ • public: • void eat() { • cout << "Mammals eat..."; • }}; • class Cow: public Mammal { • public: • void eat() { • cout << "Cows eat grass..."; • }}; • int main(void) { • Cow c = Cow(); • c.eat(); • return 0;} • O p:Cows eat grass utput:
  • 29.
    5.program • C++ RuntimePolymorphism Example • // an example without the virtual keyword.
  • 30.
    5.program class Animal { •public: • void eat(){ • cout<<"Eating..."; • } • }; • class Dog: public Animal • { • public: • void eat() • { cout<<"Eating bread..."; • } • };
  • 31.
    • int main(void){ • Dog d = Dog(); • d.eat(); • return 0; • } • op:eating bread
  • 32.
    Runtime Polymorphism withData Members • Runtime Polymorphism can be achieved by data members in C++. Let's see an example where we are accessing the field by reference variable which refers to the instance of derived class. •
  • 33.
    1.#include <iostream> 2.using namespacestd; 3.class Animal { // base class declaration. 4. public: 5. string color = "Black"; 6.}; 7.class Dog: public Animal // inheriting Animal class. 8.{ 9. public: 10. string color = "Grey"; 11.}; 12.int main(void) { 13. Animal d= Dog(); 14. cout<<d.color; 15.} Output: Black
  • 34.
    Virtual Function inC++ • A virtual function is a member function which is declared within a base class and is re- defined(Overriden) by a derived class. • When you refer to a derived class object using a pointer or a reference to the base class, • you can call a virtual function for that object and execute the derived class’s version of the function. •
  • 35.
    Rules for VirtualFunctions • Virtual functions cannot be static. • A virtual function can be a friend function of another class. • Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism. • The prototype of virtual functions should be the same in the base as well as derived class. • They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used. • A class may have virtual destructor but it cannot have a virtual constructor.
  • 36.
    • class A •{ • public: • void display() • { int x=5; • cout << "Value of x is : " << x; • } • }; • class B: public A • { public: • void display() • { int y = 10; • cout << "Value of y is : " <<y; • } • };
  • 37.
    • int main() •{ • A *a; //base class • B b; //derived • a = &b; • a->display(); • return 0; • } • Output: • Value of x is : 5 • In the above example, * 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
  • 38.
    • C++ virtualfunction Example • Let's see the simple example of C++ virtual function used to invoked the derived class in a program. • #include <iostream> • { • public: • virtual void display() • { • cout << "Base class is invoked"<<endl; • } • }; • class B:public A • { • public: • void display() • { • cout << "Derived Class is invoked"<<endl; • } • };
  • 39.
    • int main() •{ • A* a; //pointer of base class • B b; //object of derived class • a = &b; • a->display(); //Late Binding occurs • } • Output: • Derived Class is invoked • Or