0% found this document useful (0 votes)
26 views17 pages

Chapter 3 (Polymorphism)

Uploaded by

yogiabhay030
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views17 pages

Chapter 3 (Polymorphism)

Uploaded by

yogiabhay030
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Polymorphism

Polymorphism word is the combination of "poly," which means many + "morphs," which
means forms, which together means many forms.

In simple words, we can define polymorphism as the ability of a message to be displayed


in more than one form.

A real-life example of polymorphism is a person who at the same time can have different
characteristics. A man at the same time is a father, a husband, and an employee. So the
same person exhibits different behavior in different situations. This is called
polymorphism. Polymorphism is considered one of the important features of Object-
Oriented Programming.

Types of Polymorphism
 Compile-time Polymorphism
 Runtime Polymorphism

Compile Time Polymorphism

Compile-time polymorphism is done by overloading an operator or function. It is also


known as "static" or "early binding".

Why is it called compile-time polymorphism?

Overloaded functions are called by comparing the data types and number of parameters. This
type of information is available to the compiler at the compile time. Thus, the suitable
function to be called will be chosen by the C++ compiler at compilation time.

Function Overloading

When we have two functions with the same name but different parameters, different
functions are called depending on the number and data types of parameters. This is known
as function overloading
Function Overloading can be achieved through the following two cases:

 The names of the functions and return types are the same but differ in the type of
arguments.
 The name of the functions and return types are the same, but they differ in the number
of arguments.

 Example of Parameters have a different number


#include <iostream>
using namespace std;

void add(int a, int b)


{
cout << "sum = " << (a + b);
}

void add(int a, int b, int c)


{
cout << endl << "sum = " << (a + b + c);
}

// Driver code
int main()
{
add(10, 2);
add(5, 6, 4);

return 0;
}

 Example of Parameters should have a different type


#include <iostream>
using namespace std;

void add(int a, int b)


{
cout << "sum = " << (a + b);
}

void add(double a, double b)


{
cout << endl << "sum = " << (a + b);
}

// Driver code
int main()
{
add(10, 2);
add(5.3, 6.2);

return 0;
}

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.

To assign more than one operation on same operator is known as operator


overloading.

You can write operator in two ways:

1. Class Function

2. Friend Function

There are two types of Operator Overloading

1. Unary Operator

2. Binary Operator

1. Unary Operator

A operator which contain only one operand is known as Unary Operator.

Syntax:

1.Class Function

return_type operator operator_symbol()

//Body;

2. Friend Function

Syntax:
friend return_type operator operator_symbol( arg);

Here,

returnType - the return type of the function


operator - a special keyword
symbol - the operator we want to overload (+, <, -, ++, etc.)
arguments - the arguments passed to the function

Example using Class Function

Class Demo

int a,b;

public:

Demo(int x,int y)

a=x;

b=y;

void operator -()

a=-a;

b=-b;

void show()

cout<<”A”<<a<<” “<<”B”<<b<<endl;

};
int main()

Demo d(-20,10);

d.show();

-d;

d.show()

return 0;

************************************************************************

Example using Friend Function

Class Demo

int a,b;

public:

Demo(int x,int y)

a=x;

b=y;

friend void operator -( Demo &obj);

Void show()

cout<<”A”<<a<<” “<<”B”<<b<<endl;

};

void operator-( Demo &obj)


{

obj.a=-obj.a;

obj.b=-obj.b;

int main()

Demo d(-20,10);

d.show();

-d;

d.show()

return 0;

***********************************************************************

Binary Operator

A operator which contain two operand is known as Binary Operator.

Syntax

1. Class Funcion

return_type operator operator_symbol( Argument List) // only one arugment

//Body;

2. Friend Function

Syntax:

friend return_type operator operator_symbol( arg);// we can pass only two argument

Example of Binary Function using Class Function


Class Demo

int a,b;

public:

Demo()

Demo(int x,int y)

a=x;

b=y;

Demo operator +(Demo &obj)

Demo temp;

temp.a=a+obj.a;

temp.b=b+obj.b;

return temp;

};

int main()

Demo ob(10,20),ob1(20,40),ob2;

ob2=ob+ob1;

ob2.show()

return 0;
}

Example of Binary Function using Friend Function

Class Demo

int a,b;

public:

Demo()

Demo(int x,int y)

a=x;

b=y;

friend Demo operator +(Demo &obj, Demo &obj1);

};

friend Demo operator +(Demo &obj, Demo &obj1)

Demo temp;

temp.a=obj.a+obj1.a;

temp.b=obj.b+obj1.b;

return temp;

int main()

Demo ob(10,20),ob1(20,40),ob2;
ob2=ob+ob1;

ob2.show()

return 0;

*********************************************************************

Criteria/Rules to Define the Operator Function

1. In the case of a non-static member function, the binary operator should have only one
argument and the unary should not have an argument.
2. In the case of a friend function, the binary operator should have only two arguments
and the unary should have only one argument.
3. Operators that cannot be overloaded are .* :: ?:
4. Operators that cannot be overloaded when declaring that function as friend function
are = () [] ->.
5. The operator function must be either a non-static (member function), global free
function or a friend function.

Almost all operators can be overloaded except a few. Following is the list of operators that
cannot be overloaded.
sizeof
typeid
Scope resolution (::)
Class member access operators (.(dot), .* (pointer to member operator))
Ternary or conditional (?:)

**************************************************************************

Runtime Polymorphism

In runtime polymorphism, the compiler resolves the object at run time and then it decides
which function call should be associated with that object. It is also known as dynamic or late
binding polymorphism. This type of polymorphism is executed through virtual functions and
function overriding. All the methods of runtime polymorphism get invoked during the run
time.

Method overriding is an application of run time polymorphism where two or more functions
with the same name, arguments, and return type accompany different classes of the same
structure.

Runtime polymorphism is known to be better for dealing with complex problems since all
the methods and details turn up during the runtime itself.
The implementation of run time polymorphism can be achieved in two ways:

 Function overriding
 Virtual functions

Ways to Implement Run-time Polymorphism in C++


In C++, you can implement run-time polymorphism in two ways. In this section, you will see
both of them in detail.

 Function Overriding

Function overriding takes place when your derived class and base class both contain a
function having the same name. Along with the same name, both the functions should have
the same number of arguments as well as the same return type. The derived class inherits the
member functions and data members from its base class. So to override a certain
functionality, you must perform function overriding. It is achieved during the run time.

Functions that are overridden acquire different scopes. For function overriding, inheritance is
a must. It can only happen in a derived class. If a class is not inherited from another class,
you can not achieve function overriding. To sum up, a function is overridden when you want
to achieve a task supplementary to the base class function.

Example
#include <iostream>

using namespace std;

// define a base class

class bird

public:

// display function of the base class

void display()

{
cout << "I am the display function of the base class";

cout << "\n\n";

};

class parrot:public bird

public:

// display function of the serived class

// this function will display()

// of base class override at run time

void display()

cout << "I am the display function of the derived class";

cout << "\n\n";

};

int main()

// create objects of base and child classes

bird b;

parrot p;
// call the diplay() function

b.display();

p.display();

 Virtual Functions

Virtual functions are the member functions of the base class which are overridden in a
derived class. When you make a call to such a function by using a pointer or reference to the
base class, the virtual function is called and the derived class’s version of the function gets
invoked.

Some Key Points About Virtual Functions

 Virtual functions are only dynamic


 They are declared within a base class by using the keyword “virtual”
 These functions are called during run time
 Virtual functions are always declared with a base class and overridden in a child class
 Virtual functions can exist in the absence of inheritance. In that case, the base class
version of the function will be called
Example

#include <iostream>

using namespace std;

// define a base class bird

class bird {

public:

// virtual function

virtual void display()

{
cout << "This is display in bird class." << "\n\n";

void print()

cout << "This is show in bird class." << "\n\n";

};

// define a child class parrot

class parrot : public bird {

public:

void display()

cout << "This is display in parrot class." << "\n\n";

void print()

cout << "This is show in parrot class." << "\n\n";

};

int main()

{
// create a reference of class bird

bird* brd;

parrot p;

brd = &p;

// this will call the virtual function

brd->display();

// this will call the non-virtual function

brd->print();

return 0;

Compile-Time vs. Run-Time Polymorphism in C++

The key differences between compile-time polymorphism and run-time polymorphism are
summarised below:
COMPILE-TIME RUN-TIME

Compile-time polymorphism is also Run-time polymorphism is


known as static or early binding also known as dynamic or late
polymorphism. binding polymorphism.

The function calls are resolved by the The function calls are not
compiler. resolved by the compiler.

Compile-time polymorphism provides In contrast, run-time


less flexibility to the programmers since polymorphism is more flexible
everything is executed during since everything is executed
compilation. during run-time.

It can be implemented through


It can be implemented through function
virtual functions and function
overloading and operator overloading.
overriding.

Method overriding is an
Method overloading is an application of
application of run time
compile-time polymorphism where the
polymorphism where two or
same name can be commissioned
more functions with the same
between more than one method of
name, arguments, and return
functions having different arguments or
type accompany different
signatures and the same return types.
classes of the same structure.

This method has a much faster execution This method has a


rate since all the methods that need to be comparatively slower
executed are called during compile time. execution rate since all the
methods that need to be
executed are called during the
run time.

This method is known to be


This method is less preferred for
better for dealing with
handling compound problems since all
compound problems since all
the methods and details come to light
the methods and details turn up
only during the compile time.
during the run time.

You might also like