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

Unit 4-Polymorphism

Uploaded by

amrutachougale
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)
29 views

Unit 4-Polymorphism

Uploaded by

amrutachougale
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

Object Oriented Programming using c++

Unit 4:- Polymorphism

Concept of Polymorphism:-
The word “polymorphism” means having 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.

Types of Polymorphism
 Compile-time Polymorphism
 Runtime Polymorphism

1. Compile-Time Polymorphism or Static Polymorphism


This type of polymorphism is achieved by function overloading or operator overloading.
A. Function Overloading
When there are multiple functions with the same name but different parameters, then the functions are
said to be overloaded, hence this is known as Function Overloading. Functions can be overloaded
by changing the number of arguments or/and changing the type of arguments. In simple terms, it is a
feature of object-oriented programming providing many functions that have the same name but
distinct parameters when numerous tasks are listed under one function name. There are certain Rules
of Function Overloading that should be followed while overloading a function.
Below is the C++ program to show function overloading or compile-time polymorphism:

// C++ program to demonstrate


// function overloading or
// Compile-time Polymorphism
#include <bits/stdc++.h>

using namespace std;


class Geeks {

Mrs. P.D.Titavekar 1
Object Oriented Programming using c++
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;
}
};

// Driver code
int main()
{
Geeks obj1;

// Function being called depends


// on the parameters passed
// func() is called with int value
obj1.func(7);

// func() is called with double value


obj1.func(9.132);

// func() is called with 2 int values


obj1.func(85, 64);
return 0;
}
Output
value of x is 7
value of x is 9.132
value of x and y is 85, 64
Explanation: In the above example, a single function named function func() acts differently in three
different situations, which is a property of polymorphism.

B. 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
Mrs. P.D.Titavekar 2
Object Oriented Programming using c++
single operator ‘+’, when placed between integer operands, adds them and when placed between
string operands, concatenates them.
Below is the C++ program to demonstrate operator overloading:

// C++ program to demonstrate


// Operator Overloading or
// Compile-Time Polymorphism
#include <iostream>
using namespace std;

class Complex {
private:
int real, imag;

public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}

// This is automatically called


// when '+' is used with between
// two Complex objects
Complex operator+(Complex const& obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);

// An example call to "operator+"


Complex c3 = c1 + c2;
c3.print();
}
Output
12 + i9
Explanation: In the above example, the operator ‘+’ is overloaded. Usually, this operator is used to
add two numbers (integers or floating point numbers), but here the operator is made to perform the
addition of two imaginary or complex numbers.

2. Runtime Polymorphism

Mrs. P.D.Titavekar 3
Object Oriented Programming using c++
This type of polymorphism is achieved by Function Overriding. Late binding and dynamic
polymorphism are other names for runtime polymorphism. The function call is resolved at runtime
in runtime polymorphism. In contrast, with compile time polymorphism, the compiler determines
which function call to bind to the object after deducing it at runtime.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the member functions of
the base class. That base function is said to be overridden.

Runtime Polymorphism with Data Members


Runtime Polymorphism cannot be achieved by data members in C++. Let’s see an example where we
are accessing the field by reference variable of parent class which refers to the instance of the derived
class.
// C++ program for function overriding with data members
#include <bits/stdc++.h>
using namespace std;

// base class declaration.


class Animal {
public:
string color = "Black";
};

// inheriting Animal class.


class Dog : public Animal {
public:
string color = "Grey";
};

// Driver code
int main(void)
{
Animal d = Dog(); // accessing the field by reference
// variable which refers to derived

Mrs. P.D.Titavekar 4
Object Oriented Programming using c++
cout << d.color;
}

Output
Black

B. Virtual Function
A virtual function is a member function that is declared in the base class using the keyword virtual
and is re-defined (Overridden) in the derived class.
Some Key Points About Virtual Functions:
Virtual functions are Dynamic in nature.
They are defined by inserting the keyword “virtual” inside a base class and are always declared with a
base class and overridden in a child class
A virtual function is called during Runtime
Below is the C++ program to demonstrate virtual function:

1.// C++ Program to demonstrate


// the Virtual Function
#include <iostream>
using namespace std;

// Declaring a Base class


class GFG_Base {

public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function"
<< "\n\n";
}

void print()
{
cout << "Called GFG_Base print function"
<< "\n\n";
}
};

// Declaring a Child Class


class GFG_Child : public GFG_Base {

public:
void display()
{
cout << "Called GFG_Child Display Function"
<< "\n\n";
}

void print()
{
Mrs. P.D.Titavekar 5
Object Oriented Programming using c++
cout << "Called GFG_Child print Function"
<< "\n\n";
}
};

// Driver code
int main()
{
// Create a reference of class GFG_Base
GFG_Base* base;

GFG_Child child;

base = &child;

// This will call the virtual function


base->GFG_Base::display();

// this will call the non-virtual function


base->print();
}

Output
Called virtual Base Class function

Called GFG_Base print function


2. // C++ program for virtual function overriding
#include <bits/stdc++.h>
using namespace std;

class base {
public:
virtual void print()
{
cout << "print base class" << endl;
}

void show() { cout << "show base class" << endl; }


};

class derived : public base {


public:
// print () is already virtual function in
// derived class, we could also declared as
// virtual void print () explicitly
void print() { cout << "print derived class" << endl; }

void show() { cout << "show derived class" << endl; }


};

// Driver code
Mrs. P.D.Titavekar 6
Object Oriented Programming using c++
int main()
{
base* bptr;
derived d;
bptr = &d;

// Virtual function, binded at


// runtime (Runtime polymorphism)
bptr->print();

// Non-virtual function, binded


// at compile time
bptr->show();

return 0;
}

Output
print derived class
show base class

this Pointer:-
To understand ‘this’ pointer, it is important to know how objects look at functions and data members
of a class.
Each object gets its own copy of the data member.
All-access the same function definition as present in the code segment.

Following are the situations where ‘this’ pointer is used:


1) When local variable’s name is same as member’s name

#include<iostream>
using namespace std;

/* local variable is same as a member's name */


class Test
{
private:
int x;
public:
void setX (int x)
{
// The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};

int main()

Mrs. P.D.Titavekar 7
Object Oriented Programming using c++
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
Output:
x = 20

2) To return reference to the calling object


/* Reference to the calling object can be returned */
Test& Test::func ()
{
// Some processing
return *this;
}

When a reference to a local object is returned, the returned reference can be used to chain function
calls on a single object.
#include<iostream>
using namespace std;

class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()
{
Test obj1(5, 5);

// Chained function calls. All calls modify the same object


// as the same object is returned by reference
obj1.setX(10).setY(20);

obj1.print();
return 0;
}

Output:
x = 10 y = 20

Mrs. P.D.Titavekar 8
Object Oriented Programming using c++
Exercise:
Predict the output of following programs. If there are compilation errors, then fix them.
Question 1

#include<iostream>
using namespace std;

class Test
{
private:
int x;
public:
Test(int x = 0) { this->x = x; }
void change(Test *t) { this = t; }
void print() { cout << "x = " << x << endl; }
};

int main()
{
Test obj(5);
Test *ptr = new Test (10);
obj.change(ptr);
obj.print();
return 0;
}

Question 2
#include<iostream>
using namespace std;

class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
static void fun1() { cout << "Inside fun1()"; }
static void fun2() { cout << "Inside fun2()"; this->fun1(); }
};

int main()
{
Test obj;
obj.fun2();
return 0;
}

Question 3
#include<iostream>
using namespace std;
Mrs. P.D.Titavekar 9
Object Oriented Programming using c++

class Test
{
private:
int x;
int y;
public:
Test (int x = 0, int y = 0) { this->x = x; this->y = y; }
Test setX(int a) { x = a; return *this; }
Test setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()
{
Test obj1;
obj1.setX(10).setY(20);
obj1.print();
return 0;
}

Question 4
#include<iostream>
using namespace std;

class Test
{
private:
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
void setX(int a) { x = a; }
void setY(int b) { y = b; }
void destroy() { delete this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};

int main()
{
Test obj;
obj.destroy();
obj.print();
return 0;
}

Pointers to derived classes in c++:-


A pointer is a data type that stores the address of other data types. Pointers can be used for base
objects as well as objects of derived classes. A pointer to the object of the derived class and a pointer
to the object of the base class are type-compatible (may be used in different ways).

Mrs. P.D.Titavekar 10
Object Oriented Programming using c++
The pointer of Base Class pointing different objects of the derived class

Approach:
 A derived class is a class that takes some properties from its base class.
 It is true that a pointer of one class can point to another class, but classes must be a base and
derived class, then it is possible.
 To access the variable of the base class, a base class pointer will be used.
 So, a pointer is a type of base class, and it can access all, public function and variables of the
base class since the pointer is of the base class, this is known as a binding pointer.
 In this pointer base class is owned by the base class but points to the derived class object.
The same works with derived class pointer, values are changed.
Example:
// C++ program to Demonstrate the
// implementation of the base class
// pointer pointing to derived class
#include <iostream>
using namespace std;

// Base Class
class BaseClass {
public:
int var_base;

// Function to display the base


// class members
void display()
{
cout << "Displaying Base class"
<< " variable var_base: " << var_base << endl;
}
};

// Class derived from the Base Class


class DerivedClass : public BaseClass {
public:
int var_derived;

// Function to display the base

Mrs. P.D.Titavekar 11
Object Oriented Programming using c++
// and derived class members
void display()
{
cout << "Displaying Base class"
<< "variable var_base: " << var_base << endl;
cout << "Displaying Derived "
<< " class variable var_derived: "
<< var_derived << endl;
}
};

// Driver Code
int main()
{
// Pointer to base class
BaseClass* base_class_pointer;
BaseClass obj_base;
DerivedClass obj_derived;

// Pointing to derived class


base_class_pointer = &obj_derived;

base_class_pointer->var_base = 34;

// If you uncomment this line of code this will cause


// the following error As base-class pointer cannot
// access the derived class variable.
// base_class_pointer->var_derived = 98;
// output: error: ‘class BaseClass’ has no member named
// ‘var_derived’

// Calling base class member function


base_class_pointer->display();

base_class_pointer->var_base = 3400;
base_class_pointer->display();

DerivedClass* derived_class_pointer;
derived_class_pointer = &obj_derived;
derived_class_pointer->var_base = 9448;
derived_class_pointer->var_derived = 98;
derived_class_pointer->display();

return 0;
}

Output:-
Displaying Base class variable var_base: 34
Displaying Base class variable var_base: 3400
Displaying Base classvariable var_base: 9448
Displaying Derived class variable var_derived: 98
Mrs. P.D.Titavekar 12
Object Oriented Programming using c++

Conclusion:
A pointer to a derived class is a pointer of a base class pointing to a derived class, but it will hold its
aspect.
This pointer of the base class will be able to temper functions and variables of its own class and can
still point to the derived class object.

Virtual Function in C++


A virtual function (also known as virtual methods) is a member function that is declared within a base
class and is re-defined (overridden) 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 method.
Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for the function call.
 They are mainly used to achieve Runtime polymorphism.
 Functions are declared with a virtual keyword in a base class.
 The resolving of a function call is done at runtime.
Rules for Virtual Functions
The rules for the virtual functions in C++ are as follows:
 Virtual functions cannot be static.
 A virtual function can be a friend function of another class.
 Virtual functions should be accessed using a pointer or reference of base class type to achieve
runtime polymorphism.
 The prototype of virtual functions should be the same in the base as well as the 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 a virtual destructor but it cannot have a virtual constructor.
Compile time (early binding) VS runtime (late binding) behavior of Virtual Functions
Consider the following simple program showing the runtime behavior of virtual functions.
// C++ program to illustrate
// concept of Virtual Functions

#include <iostream>
using namespace std;

class base {
public:
virtual void print() { cout << "print base class\n"; }

void show() { cout << "show base class\n"; }


};

class derived : public base {


public:
void print() { cout << "print derived class\n"; }

void show() { cout << "show derived class\n"; }


};

Mrs. P.D.Titavekar 13
Object Oriented Programming using c++

int main()
{
base* bptr;
derived d;
bptr = &d;

// Virtual function, binded at runtime


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();

return 0;
}
Output
print derived class
show base class

Explanation: Runtime polymorphism is achieved only through a pointer (or reference) of the base
class type. Also, a base class pointer can point to the objects of the base class as well as to the objects
of the derived class. In the above code, the base class pointer ‘bptr’ contains the address of object ‘d’
of the derived class.

Pure Virtual Functions in C++


A pure virtual function (or abstract function) in C++ is a virtual function for which we can have an
implementation, But we must override that function in the derived class, otherwise, the derived class
will also become an abstract class. A pure virtual function is declared by assigning 0 in the
declaration.
Example of Pure Virtual Functions
// An abstract class
class Test {
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;

/* Other members */
};
Example
A pure virtual function is implemented by classes that are derived from an Abstract class.
// C++ Program to illustrate the abstract class and virtual
// functions
#include <iostream>
using namespace std;

class Base {
// private member variable
int x;

Mrs. P.D.Titavekar 14
Object Oriented Programming using c++
public:
// pure virtual function
virtual void fun() = 0;

// getter function to access x


int getX() { return x; }
};

// This class inherits from Base and implements fun()


class Derived : public Base {
// private member variable
int y;

public:
// implementation of the pure virtual function
void fun() { cout << "fun() called"; }
};

int main(void)
{
// creating an object of Derived class
Derived d;

// calling the fun() function of Derived class


d.fun();

return 0;
}
Output
fun() called

1. We can have pointers and references of abstract class type.


For example, the following program works fine.

// C++ program that demonstrate that


// we can have pointers and references
// of abstract class type.

#include <iostream>
using namespace std;

class Base {
public:
// pure virtual function
virtual void show() = 0;
};

class Derived : public Base {


public:
// implementation of the pure virtual function
void show() { cout << "In Derived \n"; }
Mrs. P.D.Titavekar 15
Object Oriented Programming using c++
};

int main(void)
{
// creating a pointer of type
// Base pointing to an object
// of type Derived
Base* bp = new Derived();

// calling the show() function using the


// pointer
bp->show();

return 0;
}
Output
In Derived
2. An abstract class can have constructors.
For example, the following program compiles and runs fine.
// C++ program to demonstrate that
// an abstract class can have constructors.

#include <iostream>
using namespace std;

// An abstract class with constructor


class Base {
protected:
// protected member variable
int x;

public:
// pure virtual function
virtual void fun() = 0;

// constructor of Base class


Base(int i)
{
x = i;
cout << "Constructor of base called\n";
}
};

class Derived : public Base {


// private member variable
int y;

public:
// calling the constructor of Base class
Derived(int i, int j)
: Base(i)
Mrs. P.D.Titavekar 16
Object Oriented Programming using c++
{
y = j;
}

// implementation of pure virtual function


void fun()
{
cout << "x = " << x << ", y = " << y << '\n';
}
};

int main(void)
{
// creating an object of Derived class
Derived d(4, 5);

// calling the fun() function of Derived class


d.fun();

// creating an object of Derived class using


// a pointer of the Base class
Base* ptr = new Derived(6, 7);

// calling the fun() function using the


// pointer
ptr->fun();

return 0;
}
Output
Constructor of base called
x = 4, y = 5
Constructor of base called
x = 6, y = 7

Mrs. P.D.Titavekar 17

You might also like