Name of staff:- Prof. Bhandare P.S.
Chapter 6
polymorphism
-by-
Prof. Bhandare P. S.
SVERI’s COE(Poly), Pandharpur
Chapter 6: Polymorphism 1
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
Syllabus:
6.1 Introduction, Types of polymorphism: Compile time, Run time
6.2 Compile time Polymorphism: Function overloading, operator
overloading: Overloading unary and binary operators, Rules for operator
overloading.
6.3 Run time polymorphism: Virtual functions, rules for virtual functions,
pure virtual function.
Assignment No 4.
1. Give any example where runtime polymorphism can be used.
2. State any two types of polymorphism.
3. What is pure virtual function ?
4. Define polymorphism. List types of polymorphism.
5. Enlist any four operators which can not be overloaded.
6. List types of polymorphism.
7. State any two rules for overloading the operator.
8. What is polymorphism ? Explain with one example.
9. What is need of virtual function? Explain with example.
10. State any four rules of operator overloading.
11. What is difference between compile time polymorphism and run time polymorphism?
12. Differentiate between compile time & run time polymorphism.
13. Explain any four rules for virtual function.
14. Compare static and dynamic binding.
15. Write a program showing use of Run time polymorphism i.e. virtual functions.
16. Write a program showing the use of function overloading.
17. Write a program to declare a class distance having data members feet & inches.
Overload unary '_' operator so that when it is used with object of this class, it
will decrement values of inches by 1
Chapter 6: Polymorphism 2
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
18. Write a program to calculate area of circle and area of rectangle using function
overloading.
19. Write a program to overload binary ++ operator
20. Write a program to show use of virtual function.
21. Create class shape. Derive two class triangle and rectangle from class shape. Write
appropriate functions in both classes to accept dimensions and calculate area. Here
make area ( ) function virtual which is common to all and will calculate area of both
rectangle and triangle. Display area of both.
22. Write a program using function overloading to calculate addition of ten integer
numbers and five float numbers.
Chapter 6: Polymorphism 3
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
About title of chapter :
The title polymorphism gives idea about the new concept defined in C++.
In this chapter we will get information about concept of polymorphism in
C++.
In this chapter students are going to learn new programming approach.
Central Idea of chapter
Central Idea behind including this chapter in subject is that the student
will importance of pointer for the classes in OOP.
Also Student will learn how programming can be organized in C++
language with the help of polymorphism.
Importance of chapter :
Studying this chapter is important is because this chapter introduce new
concept in OOP language.
Also this chapter include types of polymorphism.
Also it will include different programs for polymorphism.
Objectives of the chapter
To study concepts polymorphism.
To study types of polymorphism.
To study operator overloading.
To study function overloading.
To study function overriding.
To study virtual function.
To study pure virtual function.
Chapter 6: Polymorphism 4
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
Introduction
Polymorphism is in short the ability to call different functions by just using one type
of function call.
It is a lot useful since it can group classes and their functions together.
It is the most important part of Object-Oriented Programming.
Polymorphism is the core of object-oriented programming .
C++ supports polymorphism by allowing member functions defined in classes to be
overridden with member functions having the same names, but different
implementations, in derived classes.
If the function called is a virtual member function, the member function associated
with the actual object pointed to is called dynamically at run time.
If the function is non-virtual, the call will have been statically bound to the member
function of the reference's class at compile time
C++ Overloading
C++ allows you to specify more than one definition for a function name or an
operator in the same scope, which is called function overloading and operator
overloading respectively.
An overloaded declaration is a declaration that had been declared with the same name
as a previously declared declaration in the same scope, except that both declarations
have different arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most
appropriate definition to use by comparing the argument types you used to call the
function or operator with the parameter types specified in the definitions.
The process of selecting the most appropriate overloaded function or operator is
called overload resolution.
Function overloading in C++:
You can have multiple definitions for the same function name in the same scope.
The definition of the function must differ from each other by the types and/or the
number of arguments in the argument list.
You can not overload function declarations that differ only by return type.
Following is the example where same function print() is being used to print different
data types:
Chapter 6: Polymorphism 5
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
class printData
{
public:
void print(int i) {
cout << "Printing int: " << i << endl;
}
void print(double f) {
cout << "Printing float: " << f << endl;
}
void print(char* c) {
cout << "Printing character: " << c << endl;
}
};
int main(void)
{
printData pd;
// Call print to print integer
pd.print(5);
// Call print to print float
pd.print(500.263);
// Call print to print character
pd.print("Hello C++");
Chapter 6: Polymorphism 6
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
return 0;
}
When the above code is compiled and executed, it produces the following result:
Printing int: 5
Printing float: 500.263
Printing character: Hello C++
Operators overloading in C++:
You can redefine or overload most of the built-in operators available in C++.
Thus a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names the keyword operator followed
by the symbol for the operator being defined.
Like any other function, an overloaded operator has a return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns
final Box object.
Most overloaded operators may be defined as ordinary non-member functions or as
class member functions.
In case we define above function as non-member function of a class then we would
have to pass two arguments for each operand as follows:
Box operator+(const Box&, const Box&);
Following is the example to show the concept of operator over loading using a
member function.
Here an object is passed as an argument whose properties will be accessed using this
object, the object which will call this operator can be accessed using this operator as
explained below:
Chapter 6: Polymorphism 7
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
Overloadable/Non-overloadableOperators:
+ - * / % ^
& | ~ ! , =
< > <= >= ++ --
<< >> == != && ||
+= -= /= %= ^= &=
|= *= <<= >>= [] ()
-> ->* new new [] delete delete []
Following is the list of operators, which can not be overloaded:
:: .* . ?:
#include <iostream>
class Box
{
public:
double getVolume(void)
{
return length * breadth * height;
Chapter 6: Polymorphism 8
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
}
void setLength( double len )
{
length = len;
}
void setBreadth( double bre )
{
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b)
{
Box box;
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main( )
Chapter 6: Polymorphism 9
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
Box Box3; // Declare Box3 of type Box
double volume = 0.0
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
Box3 = Box1 + Box2;
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
}
Rules for operator overloading
1) Only built-in operators can be overloaded. New operators can not be created.
2) Arity of the operators cannot be changed.
3) Precedence and associativity of the operators cannot be changed.
Chapter 6: Polymorphism 10
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
4) Overloaded operators cannot have default arguments except the function call
operator () which can have default arguments.
5) Operators cannot be overloaded for built in types only. At least one operand must
be used defined type.
6) Assignment (=), subscript ([]), function call (“()”), and member selection (->)
operators must be defined as member functions
7) Except the operators specified in point 6, all other operators can be either member
functions or a non member functions.
8 ) Some operators like (assignment)=, (address)& and comma (,) are by default
overloaded.
Virtual Function:
A virtual function is a function in a base class that is declared using the keyword
virtual.
Defining in a base class a virtual function, with another version in a derived class,
signals to the compiler that we don't want static linkage for this function.
What we do want is the selection of the function to be called at any given point in the
program to be based on the kind of object for which it is called.
This sort of operation is referred to as dynamic linkage, or late binding.
Rules For Virtual Functions:
1. The virtual function should not be static and must be a member of a class.
2. The virtual function may be declared as a friend for another class. An object pointer
can access the virtual functions.
3. A constructor cannot be declared as virtual, but a destructor can be declared as
virtual.
4. The virtual function should be defined in the public section of the class. It is also
possible to define the virtual function outside the class.
In such a case, the declaration is done inside the class, and the definition is outside the
class. The virtual keyword is used in the declaration and not in the function
declaration.
5. It is also possible to return a value from virtual functions similar to other functions.
6. The prototype of the virtual function in the base class and derived class should be
exactly the same. In case of a mismatch, the compiler neglects the virtual function
mechanism and treats these functions as overloaded functions.
Chapter 6: Polymorphism 11
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
7. Arithmetic operations cannot be used with base class pointers.
8. If a base class contains a virtual function and if the same function is not redefined
in the derived classes, in such a case, the base class function is invoked.
9. The operator keyword used for operator overloading also supports the virtual
mechanism.
Eg.
#include <iostream>
class B
{
public:
virtual void display() /* Virtual function */
{
cout<<"Content of base class.\n";
}
};
class D1 : public B
{
public:
void display()
{
cout<<"Content of first derived class.\n";
}
};
class D2 : public B
{ public: void display()
{
cout<<"Content of second derived class.\n"; }
Chapter 6: Polymorphism 12
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
};
Void main()
{
B *b;
D1 d1;
D2 d2;
/* b->display(); // You cannot use this code here because the function of base class
is virtual. */
b = &d1;
b->display(); /* calls display() of class derived D1 */
b = &d2;
b->display(); /* calls display() of class derived D2 */;
}
Pure Virtual Functions:
#include <iostream>
class Shape /* Abstract class */
{
protected: float l;
public:
void get_data() /* Note: this function is not virtual. */
{
cin>>l;
}
virtual float area() = 0; /* Pure virtual function */
};
class Square : public Shape
{
Chapter 6: Polymorphism 13
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
public:
float area()
{
return l*l;
}
};
class Circle : public Shape
{
public: float area()
{
return 3.14*l*l;
}
};
void main()
{
Square s;
Circle c;
cout<<"Enter length to calculate area of a square: ";
s.get_data();
cout<<"Area of square: "<<s.area(); cout<<"\nEnter radius to calcuate area of a
circle:";
c.get_data();
cout<<"Area of circle: "<<c.area();
}
Chapter 6: Polymorphism 14
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
Method Overloading Method Overriding
Definition In Method Overloading, Methods of In Method Overriding, sub class
the same class shares the same name have the same method with same
but each method must have different name and exactly the same
number of parameters or parameters number and type of parameters
having different types and order. and same return type as a super
class.
Meaning Method Overloading means more Method Overriding means method
than one method shares the same of base class is re-defined in the
name in the class but having derived class having same
different signature. signature.
Behavior Method Overloading is to “add” or Method Overriding is to “Change”
“extend” more to method’s behavior. existing behavior of method.
Overloading and Overriding is a kind of polymorphism.Polymorphism
means “one name, many forms”.
Polymorphism It is a compile time polymorphism. It is a run time polymorphism.
Inheritance It may or may not need inheritance It always requires inheritance in
in Method Overloading. Method Overriding.
Signature In Method Overloading, methods In Method Overriding, methods
must have different signature. must have same signature.
Relationship of In Method Overloading, relationship In Method Overriding,
Methods is there between methods of same relationship is there between
class. methods of super class and sub
class.
Criteria In Method Overloading, methods In Method Overriding, methods
have same name different signatures have same name and same
but in the same class. signature but in the different class.
No. of Classes Method Overloading does not Method Overriding requires at
require more than one class for least two classes for overriding.
overloading.
Example Class Add Class A // Super Class
{ {
int sum(int a, int b) void display(int num)
{ {
return a + b; print num ;
} }
int sum(int a) }
{ //Class B inherits Class A
return a + 10; Class B //Sub Class
} {
} void display(int num)
{
print num ;
}
}
Chapter 6: Polymorphism 15
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
Compile time Polymorphism Run time Polymorphism
In Compile time Polymorphism, call is In Run time Polymorphism, call is not
resolved by the compiler. resolved by the compiler.
It is also known as Static binding, Early It is also known as Dynamic binding, Late
binding and overloading as well. binding and overriding as well.
Overloading is compile time polymorphism Overriding is run time polymorphism
where more than one methods share the same having same method with same parameters or
name with different parameters or signature signature, but associated in a class & its
and different return type. subclass.
It is achieved by function overloading and It is achieved by virtual functions and
operator overloading. pointers.
It provides fast execution because known It provides slow execution as compare to
early at compile time. early binding because it is known at runtime.
Compile time polymorphism is less flexible Run time polymorphism is more flexible as
as all things execute at compile time. all things execute at run time.
2 marks:
1. Give any example where runtime polymorphism can be used.
2. State any two types of polymorphism.
3. What is pure virtual function?
4. Define polymorphism. List types of polymorphism.
5. Enlist any four operators which cannot be overloaded.
6. List types of polymorphism.
7. State any two rules for overloading the operator.
8. What is polymorphism? Explain with one example.
4 Marks:
1. What is need of virtual function? Explain with example.
2. Write a program using function overloading to calculate addition of ten
integer numbers and five float numbers.
3. State any four rules of operator overloading.
Chapter 6: Polymorphism 16
Subject: Object oriented programming (17432)
Name of staff:- Prof. Bhandare P.S.
4. Create class shape. Derive two class triangle and rectangle from class
shape. Write appropriate functions in both classes to accept dimensions
and calculate area. Here make area ( ) function virtual which is common to
all and will calculate area of both rectangle and triangle. Display area of
both.
5. What is difference between compile time polymorphism and run time
polymorphism?
6. Differentiate between compile time & run time polymorphism.
7. Explain any four rules for virtual function.
8. Explain various rules for overloading operators.
9. Write a program to show use of virtual function.
10. Define polymorphism. Explain any two types with example.
11.Write a program to overload unary ++ operator.
12.Differentiate between compile time polymorphism and runtime
polymorphism.
13.Write a program to calculate area of circle and area of rectangle using
function overloading.
14.State any four rules for operator overloading.
15.Why do we need virtual functions ?
16.Distinguish between run-time polymorphism & compile-time
polymorphism.
17.State any four rules for operator overloading.
18.Explain virtual function with suitable example.
19.Write a program to declare a class distance having data members feet
& inches. Overload unary '_' operator so that when it is used with
object of this class, it will decrement values of inches by 1.
20.Explain concept of virtual base class with suitable example.
21. Explain compile time polymorphism. State any two advantages of compile
time polymorphism.
22. Write a program showing the use of function overloading.
23. Compare static and dynamic binding.
24.Write a program showing use of Run time polymorphism i.e. virtual
functions.
25.Compare function overloading with function overriding.
26.Overload binary ‘>’ operator to compare the length of two strings.
27. Explain different rules of overloading operators used in constructors.
28. Define polymorphism. State various types of it.
Chapter 6: Polymorphism 17
Subject: Object oriented programming (17432)