Polymorphism.
Polymorphism.
30-09-2024 1
Contents:
❑Polymorphism
Introduction to polymorphism, types of Polymorphism, Operator
Overloading- Concept of Overloading , Operator Overloading,
Overloading Unary Operators, Overloading binary operators, Data
conversion, Type casting(implicit & explicit) pitfalls of operator
overloading and conversion, keywords, explicit and mutable. Function
overloading , Run time polymorphism –pointers to base class, Virtual
function and its significance in c++, pure virtual function and virtual
table, virtual destructor, abstract base class.
UNIT-III Polymorphism
06-10-2021 2
Department Of Computer Engineering
4.POLYMORPHISM
UNIT-III Polymorphism
06-10-2021 3
Department Of Computer Engineering
4.2 Types Of Polymorphism..
Polymorphism.
• Object Oriented programming in C++ we have two types of polymorphism :
UNIT-III Polymorphism
06-10-2021 4
Department Of Computer Engineering
4.2 Types Of Polymorphism..
Compile Time Polymorphism.
• The overloaded functions are invoked by matching the type and number of arguments.
• Compile time polymorphism this is also known as static (or early ) binding.
• Function overloading and operator overloading are perfect example of Compile time
Polymorphism
• Functions can be overloaded by change number of arguments or/ and change types of arguments,
UNIT-III Polymorphism
06-10-2021 5
Department Of Computer Engineering
3.Polymorphism..
Example: write a program of function overloading when number of arguments vary.
#include <iostream>
using namespace std;
class Cal {
public:
static int add(int a,int b)
{
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
UNIT-III Polymorphism
06-10-2021 6
Department Of Computer Engineering
3. Polymorphism..
int main(void)
{
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}
Output:
30
55
UNIT-III Polymorphism
06-10-2021 7
Department Of Computer Engineering
3. Polymorphism..
Example: write a program of function overloading with different types of argument.
#include<iostream>
using namespace std;
int mul(int,int);
float mul(float,int);
int mul(int a,int b)
{
return a*b;
}
float mul(double x, int y)
{
return x*y;
}
UNIT-III Polymorphism
06-10-2021 8
Department Of Computer Engineering
3. Polymorphism..
int main()
{
int r1 = mul(6,7);
float r2 = mul(0.2,3);
cout << "r1 is : " <<r1<< endl;
cout <<"r2 is : " <<r2<< endl;
return 0;
}
Output:
r1 is :42
r2 is :0.6
UNIT-III Polymorphism
06-10-2021 9
Department Of Computer Engineering
4.2 Types Of Polymorphism..
4.2.2 Operator 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.,
• 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.
• Function overriding in C++ is a feature that allows us to use a function in the child class
that is already present in its parent class. The child class inherits all the data members,
and the member functions present in the parent class.
UNIT-III Polymorphism
06-10-2021 13
Department Of Computer Engineering
4.2 Types Of Polymorphism..
Example: write a program to overridden with virtual functions.
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
class animal
{public:
virtual void eat()
{ cout<<"\n Eating & Drink";
}
};
class Cat : public animal
{public:
void eat()
{ cout<<"\n Drink milk";
}
}; 06-10-2021 UNIT-III Polymorphism
Department Of Computer Engineering
14
4.2 Types Of Polymorphism..
int main()
{ clrscr();
animal *a;
animal an;
Cat c;
Dog d;
a=&an;
a->eat();
a=&c;
a->eat();
a=&d;
a->eat();
UNIT-III Polymorphism
06-10-2021 15
Department Of Computer Engineering
2 Polymorphism...
getch();
return 0;
}
Output:
Eating & Drink
Drink milk
Eating bread
UNIT-III Polymorphism
06-10-2021 16
Department Of Computer Engineering
4.2 Types Of Polymorphism..
Compile time polymorphism Run time polymorphism
• The function to be invoked is known at the • The function to be invoked is known at
compile time. the run time.
• It is also known as overloading, early binding • It is also known as overriding, Dynamic
and static binding. binding and late binding.
• Overloading is a compile time polymorphism • Overriding is a run time polymorphism
where more than one method is having the where more than one method is having
same name but with the different number of the same name, number of parameters
parameters or the type of the parameters. and the type of the parameters.
• It is achieved by function overloading and • It is achieved by virtual functions and
operator overloading. pointers.
• It provides fast execution as it is known at the • It provides slow execution as it is known
compile time. at the run time.
UNIT-III Polymorphism
06-10-2021 17
Department Of Computer Engineering
4. Polymorphism.
4.3 Concept Of Overloading:
• C++ allows you to specify more than one definition for a function in the same scope which is
called function overloading and operator overloading.
• Overloading is a concept used to avoid redundant code where the same method name is used
multiple times but with a different set of parameters.
• When a method is overloaded, the method chosen will be selected at compile time. This is not the
same as virtual functions where the method is defined at runtime.
UNIT-III Polymorphism
06-10-2021 18
Department Of Computer Engineering
4. Polymorphism.
4.4 Overloading Unary Operators:
The unary operators operate on a single operand and following are the examples of Unary operators
−
•The increment (++) and decrement (--) operators.
•The unary minus (-) operator.
•The logical not (!) operator.
• Overloading Unary Operator: Let us consider to overload (-) unary operator. In unary operator
function, no arguments should be passed. It works only with one class objects.
UNIT-III Polymorphism
06-10-2021 19
Department Of Computer Engineering
4. Polymorphism.
Example:
// Overload ++ when used as prefix and postfix
#include <iostream>
using namespace std;
class Count
{
private:
int value;
public: //Constructor to initialize count to 5
Count():
value(5)
{}
UNIT-III Polymorphism
06-10-2021 20
Department Of Computer Engineering
4. Polymorphism.
// Overload ++ when used as prefix
void operator ++ ( )
{
++value;
} // Overload ++ when used as postfix
void operator ++ (int)
{ value++;
}
Void display()
{
cout<< "Count: " << value << endl;
}
};
UNIT-III Polymorphism
06-10-2021 21
Department Of Computer Engineering
4. Polymorphism.
int main()
{
Count count1; // Call the "void operator ++ (int)" function
count1++;
count1.display(); // Call the "void operator ++ ()" function
++count1;
count1.display();
return 0;
}
Output:
Count: 6
Count: 7
UNIT-III Polymorphism
06-10-2021 22
Department Of Computer Engineering
4. Polymorphism.
4.5 Overloading Binary Operators:
• The binary operators take two arguments and following are the examples of Binary
operators.
•we use binary operators very frequently like addition (+) operator, subtraction (-) operator
and division (/) operator.
UNIT-III Polymorphism
06-10-2021 23
Department Of Computer Engineering
4. Polymorphism.
Example : C++ Binary Operator Overloading
// C++ program to overload the binary operator +
// This program adds two complex numbers
#include <iostream>
using namespace std;
class Complex {
private:
float real;
float imag;
public: // Constructor to initialize real and imag to 0
Complex() : real(0), imag(0) {}
void input() { cout << "Enter real and imaginary parts respectively: ";
cin >> real;
cin >> imag;
UNIT-III Polymorphism
06-10-2021 24
} Department Of Computer Engineering
4. Polymorphism.
// Overload the + operator
Complex operator + (const Complex& obj) {
Complex temp;
temp.real = real + obj.real;
temp.imag = imag + obj.imag;
return temp;
}
void output() {
if (imag < 0)
cout << "Output Complex number: " << real << imag << "i";
else
cout << "Output Complex number: " << real << "+" << imag << "i";
}
};
UNIT-III Polymorphism
06-10-2021 25
Department Of Computer Engineering
4. Polymorphism.
int main() {
Complex complex1, complex2, result;
cout << "Enter first complex number:\n";
complex1.input();
cout << "Enter second complex number:\n";
complex2.input();
// complex1 calls the operator function
// complex2 is passed as an argument to the function
result = complex1 + complex2;
result.output();
return 0;
}
UNIT-III Polymorphism
06-10-2021 26
Department Of Computer Engineering
4. Polymorphism.
Output:
Enter first complex number:
Enter real and imaginary parts respectively: 9 5
Enter second complex number:
Enter real and imaginary parts respectively: 7 6
Output Complex number: 16+11i
UNIT-III Polymorphism
06-10-2021 27
Department Of Computer Engineering
4. Polymorphism.
4.6 Data Conversion:
• A user-defined data types are designed by the user to suit their requirements, the compiler
does not support automatic type conversions for such data types therefore, the user needs to
design the conversion routines by themselves if required.
UNIT-III Polymorphism
06-10-2021 28
Department Of Computer Engineering
4. Polymorphism.
•Syntax :
Class class_name
{
Public:
//……..
Class_name(data type)
{
// conversion code.
}
};
UNIT-III Polymorphism
06-10-2021 29
Department Of Computer Engineering
4. Polymorphism.
•Program: Conversion from basic type to object.
#include <iostream.h>
#include<stdio.h>
#include<conio.h>
using namespace std;
class Time // Time Class
{
int hour;
int mins;
public:
// Default Constructor
Time()
{
UNIT-III Polymorphism
06-10-2021 30
Department Of Computer Engineering
4. Polymorphism.
hour = 0;
mins = 0;
}
// Parameterized Constructor
Time(int t)
{
hour = t / 60;
mins = t % 60;
}
// Function to print the value
// of class variables
void Display()
{
UNIT-III Polymorphism
06-10-2021 31
Department Of Computer Engineering
4. Polymorphism.
cout << "Time = " << hour<< " hrs and "<< mins << " mins\n";
}
};
int main()
{ // Object of Time class
Time T1;
int dur = 95;
// Conversion of int type to
// class type
T1 = dur;
T1.Display();
return 0;
}
UNIT-III Polymorphism
06-10-2021 32
Department Of Computer Engineering
4. Polymorphism.
Output:
Time = 1 hrs and 35 mins
UNIT-III Polymorphism
06-10-2021 33
Department Of Computer Engineering
4. Polymorphism.
4.7 Type Casting(Implicit and Explicit):
• Type conversion can be done in two ways in C++, one is implicit type conversion, and
the second is explicit type conversion.
•Those conversions are done by the compiler itself, called the implicit type or automatic
type conversion.
•The conversion, which is done by the user or requires user interferences called the explicit
or user define type conversion
UNIT-III Polymorphism
06-10-2021 34
Department Of Computer Engineering
4. Polymorphism.
4.7.1 Implicit Type Conversion
• The implicit type conversion is the type of conversion done automatically by the compiler
without any human effort.
• It means an implicit conversion automatically converts one data type into another type
based on some predefined rules of the C++ compiler. Hence, it is also known as
the automatic type conversion.
For example:
int x = 20;
short int y = 5;
int z = x + y;
UNIT-III Polymorphism
06-10-2021 35
Department Of Computer Engineering
4. Polymorphism.
#include <iostream>
using namespace std;
int main ()
{
// assign the integer value
int num1 = 25;
// declare a float variable
float num2;
// convert int value into float variable using implicit conversion
num2 = num1;
cout << " The value of num1 is: " << num1 << endl;
cout << " The value of num2 is: " << num2 << endl;
return 0;
UNIT-III Polymorphism
06-10-2021 36
} Department Of Computer Engineering
4. Polymorphism.
4.7.2 Explicit Type Conversion
• Conversions that require user intervention to change the data type of one variable to
another, is called the explicit type conversion.
• Let's consider an example to convert the float data type into int type using the cast
operator of the explicit conversion in C++ language.
• Programming Example:
#include <iostream>
using namespace std;
int main ()
{
float f2 = 6.7;
// use cast operator to convert data from one type to another
UNIT-III Polymorphism
06-10-2021 38
Department Of Computer Engineering
4. Polymorphism.
UNIT-III Polymorphism
06-10-2021 39
Department Of Computer Engineering
4. Polymorphism.
2. Explicit conversion using the assignment operator
• Let's consider an example to convert the data type of one variable into
another using the assignment operator in the C++ program.
#include <iostream>
using namespace std;
int main ()
{
float num2; // declare a float variable
int num1 = 25; // initialize an int variable
num2 = (float) num1; // convert data type from int to float
cout << " The value of int num1 is: " << num1 << endl;
cout << " The value of float num2 is: " << num2 << endl;
return 0;
} 06-10-2021
UNIT-III Polymorphism
Department Of Computer Engineering
40
4. Polymorphism.
Output:
The value of int num1 is: 25
The value of float num2 is: 25.0
UNIT-III Polymorphism
06-10-2021 41
Department Of Computer Engineering
4. Polymorphism.
4.8 Keywords: Explicit and Mutable.
• The two unusual keywords: explicit and mutable They have quite different effects , but
are grouped together here because they both modify class members.
• The explicit keywords relates to data conversion but mutable has more subtle purpose.
UNIT-III Polymorphism
06-10-2021 42
Department Of Computer Engineering
4. Polymorphism.
4.8 Keywords: Explicit and Mutable.
Use of mutable keyword
• Mutable data members are those members whose values can be changed in runtime even
if the object is of constant type. It is just opposite to constant.
• Sometimes logic required to use only one or two data member as a variable and another
one as a constant to handle the data.
UNIT-III Polymorphism
06-10-2021 43
Department Of Computer Engineering
4. Polymorphism.
4.9 Pointer to Base class
• One of the key features of class inheritance is that a pointer to a derived class is type-
compatible with a pointer to its base class.
• Polymorphism is the art of taking advantage of this simple but powerful and versatile
feature.
UNIT-III Polymorphism
06-10-2021 44
Department Of Computer Engineering
4. Polymorphism.
4.10 Virtual Functions and its Significance in C++
• A Virtual function is a member function which is declared within a base class and it is
re-defined by a derived class.
• Virtual Function ensure that the correct function is called for an object , regardless of the
type of reference (or pointer) used for function call.
UNIT-III Polymorphism
06-10-2021 45
Department Of Computer Engineering
4. Polymorphism.
4.11 Pure Virtual Functions:
• If class contains at least one pure virtual functions then that class is called as abstract
class.
Virtual return_typefun_name()=0;
UNIT-III Polymorphism
06-10-2021 46
Department Of Computer Engineering
4. Polymorphism.
Virtual Functions Pure Virtual Functions
A virtual function is a member function of base class A pure virtual function is a member function of base
which can be redefined by derived class. class whose only declaration is provided in base class
and must defined derived class.
Classes are virtual function are not abstract Base class containing pure virtual function becomes
abstract.
Syntax: Syntax:
virtual<func_type> <func_name>()
{ virtual<func_type> <func_name>()=0;
// code
}
• When a class declares a virtual member function, most of the compilers add a hidden member
variable that represents a pointer to Virtual Method Table (VMT or VTable).
• We will call this pointer as vptr. This table represents an array of pointers to virtual functions.
UNIT-III Polymorphism
06-10-2021 48
Department Of Computer Engineering
4. Polymorphism.
4.13 Abstract Base class
• We cannot create objects of an abstract class. However, we can derive classes from
them, and use their data members and member functions (except pure virtual functions).
• A pure virtual function (or abstract function) in C++ is a virtual function for which we
can have implementation, But we must override that function in the derived class,
otherwise the derived class will also become abstract class .
UNIT-III Polymorphism
06-10-2021 49
Department Of Computer Engineering
4. Polymorphism.
Consider following simple example:
//abstract base class
#include <iostream>
using namespace std;
class Polygon
{ protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a;
height=b;
}
virtual int area (void) =0;
UNIT-III Polymorphism
06-10-2021 50
Department Of Computer Engineering
};
4. Polymorphism.
class Rectangle: public Polygon
{
public:
int area (void)
{ return (width * height);
}
};
class Triangle: public Polygon
{ public:
int area (void)
{ return (width * height / 2);
}
};
UNIT-III Polymorphism
06-10-2021 51
Department Of Computer Engineering
4. Polymorphism.
int main ()
{ Rectangle rect;
Triangle trgl;
Polygon * ppoly1 = ▭
Polygon * ppoly2 = &trgl;
ppoly1->set_values (4,5);
ppoly2->set_values (4,5);
cout << ppoly1->area() << '\n';
cout << ppoly2->area() << '\n';
return 0;
}
Output:
20
UNIT-III Polymorphism
06-10-2021 52
Department Of Computer Engineering
10
4. Polymorphism.
4.14 Virtual Destructor:
• Deleting a derived class object using pointer to a base class that has a non – virtual
destructor base class that has a non –virtual destructor results in undefined behaviour.
• To correct this situation the base class should be defined with the virtual destructor.
UNIT-III Polymorphism
06-10-2021 53
Department Of Computer Engineering
4. Polymorphism.
#include<iostream>
using namespace std;
class base
{
public:
virtual ~base()
{cout<<"Base class::Destructor\n";
}
};
class derived:public base
{ public:
UNIT-III Polymorphism
06-10-2021 54
Department Of Computer Engineering
4. Polymorphism.
~derived()
{ cout<<"Derived class::Destructor\n";
}
};
int main()
{ base *b=new derived;
delete b;
//derived *d;
//delete d;
return 0;
}
Output:
Derived class::Destructor
UNIT-III Polymorphism
06-10-2021 55
Base class::Destructor Department Of Computer Engineering