0% found this document useful (0 votes)
10 views

OOP-Unit 3

Please submit

Uploaded by

vekariyajay985
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

OOP-Unit 3

Please submit

Uploaded by

vekariyajay985
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

UNIT – 3:

Polymorphism
UNIT – 3: Polymorphism

3.1 Concepts of Polymorphism


Polymorphism is a popular concept in object-oriented programming (OOP), referring to the idea
that an entity in code such as a function or object can have more than one form. The word
polymorphism is derived from Greek and means "having multiple forms." Apart from computer
programming, the idea of polymorphism occurs in other real-world areas, including biology,
chemistry and drug development.

Polymorphism is one of the most important concepts in OOP. It describes the ability of
something to have or to be displayed in more than one form. The different forms arise because
these entities can be assigned different meanings and used in various ways in multiple contexts.

3.2 Compile Time and Run time polymorphism


Compile Time: The functions overloading 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.

Run time: 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.

2
UNIT – 3: Polymorphism

Difference between Compile time polymorphism and Run time polymorphism

Compile time polymorphism Run time polymorphism

The function to be invoked is known at the The function to be invoked is known at the
compile time. 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


where more than one method is having the more than one method is having the same
same name but with the different number of name, number of parameters and the type of
parameters or the type of the parameters. 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 at


compile time. the run time.

It is less flexible as mainly all the things It is more flexible as all the things execute at
execute at the compile time. the run time.

3.3 Overloading and Overriding

Function Overloading

Function Overloading is defined as the process of having two or more function with the same
name, but different in parameters is known as function overloading. In function overloading,
the function is redefined by using either different types of arguments or a different number of
arguments. It is only through these differences compiler can differentiate between the
functions.
Function overloading is performing within single class only. You cannot overload function
declarations that differ only by return type.

The advantage of Function overloading is that it increases the readability of the program
because you don't need to use different names for the same action.

3
UNIT – 3: Polymorphism

Example:

#include<iostream>
using namespace std;

class sum
{
public:
void addition(int x, int y)
{
cout<<x+y;
}

void addition(int x, double y)


{
cout<<x+y;
}

4
UNIT – 3: Polymorphism

void addition(int x, int y, int z)


{
cout<<x+y+z;
}
};

int main()
{
sum s1;
s1.addition(10,20.50);
s1.addition(10,15);
s1.addition(10,5,7);
return 0;
}

Advantages of Function Overloading


 The main advantage of function overloading is that it improves code readability and
allows code reusability.
 The use of function overloading is to save memory space, consistency, and readability.
 It speeds up the execution of the program
 Code maintenance also becomes easy.
 Function overloading brings flexibility to code.
 The function can perform different operations and hence it eliminates the use of
different function names for the same kind of operations.

Disadvantages of Function Overloading


 In function overloading, the main disadvantage is that the functions with different
return types can’t be overloaded.
 In the case of a static function, the same parameters cannot be overloaded.

Operator Overloading
Operator overloading is one of the best features of C++. By overloading the operators,
we can give additional meaning to the operators like +-*/=.,= etc., which by default are
supposed to work only on standard data types like int, float, char, void etc. It is an essential
concept in C++. It’s a type of polymorphism in which an operator is overloaded to give it the
user-defined meaning. For example '+' operator can be overloaded to perform addition on various
data types, like for Integer, String(concatenation) etc.

5
UNIT – 3: Polymorphism

What is the difference between operator functions and normal functions?


Operator functions are the same as normal functions. The only differences are, that the name
of an operator function is always the operator keyword followed by the symbol of the operator,
and operator functions are called when the corresponding operator is used.

Almost any operator can be overloaded in C++. However there are few operators which cannot
be overloaded. Operators that are not overloaded are follows

 scope operator( :: ) =
 sizeof =
 member selector( . ) =
 member pointer selector( * ) =
 ternary operator(?:)=

 Operator Overloading Syntax

 Implementing Operator Overloading

Operator overloading can be done by implementing a function which can be :

1. Member Function
2. Non-Member Function
3. Friend Function

6
UNIT – 3: Polymorphism

Operator overloading function can be a member function if the Left operand is an Object of
that class, but if the Left operand is different, then Operator overloading function must be a
non-member function.

Operator overloading function can be made friend function if it needs access to the private and
protected members of class.

 Restrictions on Operator Overloading


1. Precedence and associatively of an operator cannot be changed.
2. Numbers of Operands cannot be changed. Unary operator remains unary, binary
remains binary etc.
3. No new operators can be created, only existing operators can be overloaded.
4. Cannot redefine the meaning of a procedure. You cannot change how integers are
added.

 Overloading Arithmetic Operator


Arithmetic operators are most commonly used operator in C++. Almost all arithmetic operator
can be overloaded to perform arithmetic operation on user-defined data type. In the below
example we have overridden the + operator, to add to Time (hh:mm:ss) objects.

Example: overloading '+' Operator to add two time object

#include <iostream>

using namespace std;

class Complex {
private:
int x, y;
public:
Complex() {}
Complex(int a, int b)
{
x = a;
y = b;
}
Complex operator+(Complex obj)
{
Complex res;
res.x = x + obj.x;

7
UNIT – 3: Polymorphism

res.y = y + obj.y;
return res;
}

Complex operator*(Complex obj)


{
Complex res;
res.x = x * obj.x;
res.y = y * obj.y;
return res;
}

void print()
{
cout <<"X = "<< x <<endl<<"Y = "<< y << endl;
}
};
int main()
{
Complex c1(10, 5);
Complex c2(2, 4);

// An example call to "operator+"


Complex c3 = c1 + c2;
c3.print();
c3 = c1 * c2;
c3.print();
}

 Overloading Relational operator

You can also overload Relational operator like == , != , >= , <= etc. to compare two user-defined
object.

Example

class time
{
int hr,min,sec;
public:
time()
{
hr=0, min=0; sec=0;
}

8
UNIT – 3: Polymorphism

time(int h,int m, int s)


{
hr=h, min=m; sec=s;
}

friend bool operator==(time &t1, time &t2); //overloading '==' operator


};

bool operator== (time &t1, time &t2) //operator function


{
return ( t1.hr == t2.hr && t1.min == t2.min && t1.sec == t2.sec );
}

 Copy constructor Vs. Assignment operator


Assignment operator is used to copy the values from one object to another already existing
object. For example
time tm(3,15,45); //tm object created and initialized
time t1; //t1 object created
t1 = tm; //initializing t1 using tm
Copy constructor is a special constructor that initializes a new object from an existing object.
time tm(3,15,45); //tm object created and initialized
time t1(tm); //t1 object created and initialized using tm object

9
UNIT – 3: Polymorphism

Note :

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.

For example, X is a base class and Y is a derived class. The pointer pointing to X can also point to Y.

Class X
{ //Class body };
Class Y : public X
{ //class body };
void main(){
X *ptr; //pointer to base class
X x;
Y y;
ptr = &x; // Pointing to base class
ptr = &y; //Pointing to Derived class using base class pointer
}

Dynamic Polymorphism (Overriding)


A function is said to exhibit dynamic polymorphism when it exists in more than one
form, and calls to its various forms are resolved dynamically when the program is executed. The
term late binding refers to the resolution of the functions at run-time instead of compile time.
This feature increases the flexibility of the program by allowing the appropriate method to be
invoked, depending on the context.

Overriding
If we inherit a class into the derived class and provide a definition for one of the base class's
function again inside the derived class, then that function is said to be overridden, and this
mechanism is called Function Overriding

 Requirements for Overriding


1. Inheritance should be there. Function overriding cannot be done within a class. For this we
require a derived class and a base class.
2. Function that is redefined must have exactly the same declaration in both base and derived
class, that means same name, same return type and same parameter list.

10
UNIT – 3: Polymorphism

 Function Call Binding with class Objects

Connecting the function call to the function body is called Binding. When it is done before the
program is run, its called Early Binding or Static Binding or Compile-time Binding.

Example:

class Base
{
public:
void shaow()
{
cout << "Base class\t";
}
};

class Derived : public Base


{
public:
void show()
{
cout << "Derived Class";
}
};

int mian()
{
Base b; //Base class object
Derived d; //Derived class object
b.show(); //Early Binding Occurs
d.show(); //Early Binding Occurs
}

Output:
Base class Derived class

In the above example, we are calling the overrided function using Base class and Derived class
object. Base class object will call base version of the function and derived class's object will call
the derived version of the function.

11
UNIT – 3: Polymorphism

 Function Call Binding using Base class Pointer

When we use a Base class's pointer or reference to hold Derived class's object, then Function
call Binding gives some unexpected results.

class Base
{
public:
void show()
{
cout << "Base class";
}
};

class Derived : public Base


{
public:
void show()
{
cout << "Derived Class";
}
};

int main()
{
Base *b; //Base class pointer
Derived d; //Derived class object
b = &d; // Bind Base class pointer object with derived class object
b->show(); //Early Binding Occurs
}

Output:
Base class

In the above example, although, the object is of Derived class, still Base class's method is called.
This happens due to Early Binding.
Compiler on seeing Base class's pointer, set call to Base class's show() function, without
knowing the actual object type.

12
UNIT – 3: Polymorphism

3.5 Virtual Function


Virtual Function is a function in base class, which is overrided in the derived class, and which
tells the compiler to perform Late Binding on this function.
“Virtual” Keyword is used to make a member function of the base class Virtual.

 Problem without Virtual Keyword


class Base
{
public:
void show()
{
cout << "Base class";
}
};

class Derived : public Base


{
public:
void show()
{
cout << "Derived Class";
}
};

int main()
{
Base* b; //Base class pointer
Derived d; //Derived class object
b = &d;
b->show(); //Early Binding Occurs
}

Output:
Base class

When we use Base class's pointer to hold Derived class's object, base class pointer or
reference will always call the base version of the function

13
UNIT – 3: Polymorphism

 Using Virtual Keyword


We can make base class's methods virtual by using virtual keyword while declaring them.
Virtual keyword will lead to Late Binding of that method.

class Base
{
public:
virtual void show()
{
cout << "Base class";
}
};

class Derived : public Base


{
public:
void show()
{
cout << "Derived Class";
}
};

int main()
{
Base* b; //Base class pointer
Derived d; //Derived class object
b = &d;
b->show(); //Late Binding Occurs
}

Output:
Derived class

On using Virtual keyword with Base class's function, Late Binding takes place and the
derived version of function will be called, because base class pointer pointes to Derived class
object.

14
UNIT – 3: Polymorphism

Important Points to Remember

1. Only the Base class Method's declaration needs the Virtual Keyword, not the definition.
2. If a function is declared as virtual in the base class, it will be virtual in all its derived classes.

 Pure virtual Function

A pure virtual function is a function that has the notation "= 0" in the declaration of that
function. Why we would want a pure virtual function and what a pure virtual function looks like
is explored in more detail below.

Simple Example of a pure virtual function in C++:


class SomeClass {
public:
virtual void pure_virtual() = 0; // a pure virtual function
// note that there is no function body
};

The "= 0" portion of a pure virtual function is also known as the pure specifier, because it’s
what makes a pure virtual function “pure”. Although the pure specifier appended to the end of
the virtual function definition may look like the function is being assigned a value of 0, that
is not true. The notation "= 0" is just there to indicate that the virtual function is a pure virtual
function, and that the function has no body or definition.

Any class that has at least one pure virtual function is called an abstract class. This means
that in our example above, the SomeClass class is an abstract class. An abstract
class cannot have an instance of itself created. So, using our example class from above, the
following code would not work:

SomeClass s1; //Error! SomeClass is abstract

This also means that any class that derives from an abstract class must override the
definition of the pure virtual function in the base class, and if it doesn’t then the derived class
becomes an abstract class as well.

15
UNIT – 3: Polymorphism

 Static Vs Dynamic Polymorphism

 Static polymorphism is considered more efficient and dynamic polymorphism more


flexible.
 Statically bound methods are those methods that are bound to their calls at compile
time. Dynamic function calls are bound to the functions during run-time. This involves
the additional step of searching the functions during run-time. On the other hand, no
run-time search is required for statically bound functions.
 As applications are becoming larger and more complicated, the need for flexibility is
increasing rapidly. Most users have to periodically upgrade their software, and this
could become a very tedious task if static polymorphism is applied. This is because any
change in requirements requires a major modification in the code. In the case of
dynamic binding, the function calls are resolved at run-time, thereby giving the user the
flexibility to alter the call without having to modify the code.

 Function overloading Vs Function overriding

Points Function Overloading Function Overriding


Definition When two or more methods in a class One method is in the parent class
have distinct parameters but the same and the other is in the child class
method name, this is known as when a function is overridden, but
function overloading. they have the same parameters
and method name.
Function There should be a difference in the The function signature should not
signature number or kind of parameters. change.
Behaviour Defines several methods’ behaviours. Changes the way the procedure
behaves.
Scope of They belong to the same Class. They belong to the Multiple Class.
Function
Inheritance Even without inheritance, it can Only when a class inherits from
happen. another does it happen
Polymorphism Compile Time Run Time

Technique Code improvement method. Method for replacing code.

16

You might also like