100% found this document useful (1 vote)
9 views17 pages

C++ Polymorphism

Polymorphism in C++ refers to the ability of functions and operators to behave differently based on the context, and is categorized into compile-time (static binding) and runtime (dynamic binding) polymorphism. Compile-time polymorphism is achieved through function and operator overloading, while runtime polymorphism is achieved through function overriding and virtual functions. Virtual functions allow for dynamic binding, ensuring the correct function is called based on the object type at runtime.

Uploaded by

noopursakpal1309
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
100% found this document useful (1 vote)
9 views17 pages

C++ Polymorphism

Polymorphism in C++ refers to the ability of functions and operators to behave differently based on the context, and is categorized into compile-time (static binding) and runtime (dynamic binding) polymorphism. Compile-time polymorphism is achieved through function and operator overloading, while runtime polymorphism is achieved through function overriding and virtual functions. Virtual functions allow for dynamic binding, ensuring the correct function is called based on the object type at runtime.

Uploaded by

noopursakpal1309
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 in C++

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.
Polymorphism is one of the core concepts of Object-Oriented Programming (OOP).
It allows objects of different classes to be treated as objects of a common base class.
The term "polymorphism" means "many forms," and in C++, it enables the same
function or operator to behave differently based on the context.
Polymorphism is a feature of OOPs that allows the object to behave differently
in different conditions. In C++ we have two types of polymorphism:
1) Compile time Polymorphism – This is also known as static (or early) binding.
2) Runtime Polymorphism – This is also known as dynamic (or late) binding.

1. Compile-time Polymorphism in C++


This type of polymorphism is also referred to as static binding or early binding. It
takes place during compilation.
We use function overloading and operator overloading to achieve compile-time
polymorphism.
i. Function Overloading in C++
When there are multiple functions with same name but different parameters then
these functions are said to be overloaded. Functions can be overloaded by change in
number of arguments or/and change in type of arguments.
Function overloading is a feature of object oriented programming where two or
more functions can have the same name but different parameters.

When a function name is overloaded with different jobs it is called Function


Overloading. In Function Overloading “Function” name should be the same and the
arguments should be different.
In C++, two or more functions can have the same name if the number and/or type of
parameters are different, this is called function overloading. Thus, overloaded functions are
functions that have the same name but different parameters.
An overloaded function is called based on the number and type of parameters passed.
Thus, the compiler picks the correct function during compilation of the program.

// C++ program for function overloading


#include <iostream.h>
class Geeks
{
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;
}
};

int main() {

Geeks obj1;
// Which function is called will depend on the
parameters passed
// The first 'func' is called
obj1.func(7);

// The second 'func' is called


obj1.func(9.132);
// The third 'func' is called
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
In the above example, a single function named func acts differently in three
different situations which is the property of polymorphism.

#include <iostream>
class Math {
public:
int sum(int a, int b) {
return a + b;
}
int sum(int a, int b, int c) {
return a + b + c;
}
};
int main() {
Math obj;
cout << "Sum of 2 numbers: " << obj.sum(5, 10) << endl;
// Calls sum(int, int)
cout << "Sum of 3 numbers: " << obj.sum(5, 10, 15) << endl;
// Calls sum(int, int, int)
return 0;
}

Functions that cannot be overloaded in C++


In C++, following function declarations cannot be overloaded.
1) Function declarations that differ only in the return type. For example, the
following program fails in compilation.
#include<iostream>
class demo{
int foo() {
return 10;
}
char foo() {
return 'a';}
};
int main()
{
demo d1;
char x = d1.foo();
getchar();
return 0;
}

2) Main Function:
The entry point of a C++ program, main(), cannot be overloaded. The C++
standard specifies that there should be only one main() function.
3) Member function declarations with the same name and the name parameter-
type-list cannot be overloaded if any of them is a static member function
declaration. For example, following program fails in compilation.
#include<iostream>
class Test {
static void fun(int i) {}
void fun(int i) {}
};

int main()
{
Test t;
getchar();
return 0;
}

• Operator Overloading:
C++ also provide option to overload operators. For example, we can make the
operator (‘+’) for string class to concatenate two strings. We know that this is the
addition operator whose task is to add two operands. So a single operator ‘+’ when
placed between integer operands , adds them and when placed between string
operands, concatenates them.
Example:

// CPP program to illustrate


// Operator Overloading
#include<iostream.h>
class Complex {
public:
int real, imag;
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 obj) {
Complex res(0,0);
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call t"operator+"
c3.print();
}

• Output:
• 12 + i9
• In the above example the operator ‘+’ is overloaded. The operator ‘+’ is an addition
operator and can add two numbers(integers or floating point) but here the operator is
made to perform addition of two imaginary or complex numbers.
2. Runtime polymorphism:
This type of polymorphism is achieved by Function Overriding.
• Function overriding on the other hand 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. The function signature remains same but the working of the function
is altered to meet the needs of the derived class
What is Function Overriding in C++?
Function overriding is a type of polymorphism in which we redefine the member function
of a class which is inherited from its base class. The function signature remains same but
the working of the function is altered to meet the needs of the derived class. So, when we
call the function using its name for the parent object, the parent class function is
executed. But when we call the function using the child object, the child class version
will be executed.
Real-Life Example of Function Overriding
The best Real-life example of this concept is the Constitution of India. India took the
political code, structure, procedures, powers, and duties of government institutions and set
out fundamental rights, directive principles, and the duties of citizens of other countries and
implemented them on its own; making it the biggest constitution in the world.
Another Development real-life example could be the relationship between RBI(The
Reserve Bank of India) and Other state banks like SBI, PNB, ICICI, etc. Where the RBI
passes the same regulatory function and others follow it as it is.
Example 1:
#include <iostream>
class Base {
public:
void show() {
cout << "Base class show() function" << endl;
}
};
class Derived : public Base {
public:
void show() { // Function Overriding
cout << "Derived class show() function" << endl;
}
};

int main() {
Base b1;
B1.show();
Derived d;
d.show(); // Calls Derived class's show()
return 0;
}
Example 2:
#include <iostream>
class Base {
public:
void show() {
cout << "Base class show() function" << endl;
}
};
class Derived : public Base {
public:
void show() { // Function Overriding
cout << "Derived class show() function" << endl;
}
};
int main() {
Base *b;
Derived d;
b=&d;
b->show();
d.show(); // Calls Derived class's show()
return 0;
}
Output:
Base class show() function
Derived class show() function

Virtual Functions in C++


What is a Virtual Function?
A virtual function in C++ is a member function of a class that is declared using the virtual
keyword in the base class. It allows dynamic (runtime) polymorphism, enabling function
overriding in derived classes and ensuring the correct function is called for an object, even
when accessed through a base class pointer.
Key Characteristics of Virtual Functions
1. Declared using the virtual keyword in the base class.
2. Can be overridden in derived classes.
3. Ensures that the function call is determined at runtime (dynamic binding) rather
than at compile time (static binding).
4. Works through base class pointers or references.
5. If a base class pointer points to a derived class object, the overridden function in the
derived class is called, not the base class function.

Example 3:
#include <iostream>
class Base {
public:
virtual void show() {
cout << "Base class show() function" << endl;
}
};
class Derived : public Base {
public:
void show() { // Function Overriding
cout << "Derived class show() function" << endl;
}
};
int main() {
Base *b;
Derived d;
b=&d;
b->show();
d.show(); // Calls Derived class's show()
return 0;
}
Output:
Derived class show() function
Derived class show() function
Compile time (early binding) VS runtime (late binding) 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"; }


};

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.
Late binding (Runtime) is done in accordance with the content of the pointer (i.e.
location pointed to by pointer) and Early binding (Compile-time) is done according to
the type of pointer since the print() function is declared with the virtual keyword so it
will be bound at runtime (output is print derived class as the pointer is pointing to
object of derived class) and show() is non-virtual so it will be bound during compile
time (output is show base class as the pointer is of base type).

#include <iostream>
using namespace std;
// Base class
class Shape {
protected:
int length, width;

public:
// parameterized constructor
Shape(int l, int w)
{
length = l;
width = w;
}
int get_Area()
{
cout << "This is call to parent class area\n";
// Returning 1 in user-defined function means true
return 1;
}
};
// Derived class
class Square : public Shape {
public:
Square(int l = 0, int w = 0): Shape(l, w)
{}

int get_Area()
{
cout << "Square area: " << length * width << '\n';
return (length * width);
}
};
// Derived class
class Rectangle : public Shape {
public:
Rectangle(int l = 0, int w = 0): Shape(l, w)
{}
int get_Area()
{
cout << "Rectangle area: " << length * width
<< '\n';
return (length * width);
}
};
int main()
{
Shape* s;

// Making object of child class Square


Square sq(5, 5);

// Making object of child class Rectangle


Rectangle rec(4, 5);

s = &sq; // reference variable


s->get_Area();
s = &rec; // reference variable
s->get_Area();

return 0;

}
Output:
This is call to parent class area
This is call to parent class area
In the above example:
• We store the address of each child’s class Rectangle and Square object in s and
• Then we call the get_Area() function on it,
• Ideally, it should have called the respective get_Area() functions of the child
classes but
• Instead, it calls the get_Area() defined in the base class.
• This happens due to static linkage which means the call to get_Area() is getting
set only once by the compiler which is in the base class.
#include <fstream>
#include <iostream>
using namespace std;
class Shape {
public:
virtual void calculate()
{
cout << "Area of your Shape ";
}
// usage of virtual Destuctor to avoid memory leak
virtual ~Shape()
{
cout << "Shape Destuctor Call\n";
}
};
class Rectangle : public Shape {
public:
int width, height, area;
void calculate()
{
cout << "Enter Width of Rectangle: ";
cin >> width;
cout << "Enter Height of Rectangle: ";
cin >> height;
area = height * width;
cout << "Area of Rectangle: " << area << "\n";
}

// Virtual Destuctor for every Derived class


virtual ~Rectangle()
{
cout << "Rectangle Destuctor Call\n";
}
};

// Declaration of 2nd derived class


class Square : public Shape {
public:
int side, area;
void calculate()
{
cout << "Enter one side your of Square: ";
cin >> side;
area = side * side;
cout << "Area of Square: " << area << "\n";
}
// Virtual Destuctor for every Derived class
virtual ~Square()
{
cout << "Square Destuctor Call\n";
}
};
int main()
{
// base class pointer
Shape* S;
Rectangle r;
// initialization of reference variable
S = &r;
// calling of Rectangle function
S->calculate();
Square sq;
// initialization of reference variable
S = &sq;
// calling of Square function
S->calculate();
return 0;
}
Output:
Enter Width of Rectangle: 4
Enter Height of Rectangle: 5
Area of Rectangle: 20
Enter one side your of Square: 3
Area of Square: 9
Square Destuctor Call
Shape Destuctor Call
Rectangle Destuctor Call
Shape Destuctor Call

Virtual function vs Pure virtual function in C++


What is pure virtual function?
A pure virtual function is a virtual function declared in a base class that has no definition within
that class. It is specified by assigning = 0 in its declaration. Pure virtual functions create an abstract
class, which cannot be instantiated directly. Instead, the derived classes must provide an
implementation for these functions.
A pure virtual function is a virtual function that has no definition within the class. Let's understand the
concept of pure virtual function through an example.
In the above pictorial representation, shape is the base class while rectangle, square and circle are the
derived class. Since we are not providing any definition to the virtual function, so it will automatically
be converted into a pure virtual function.
Characteristics of a pure virtual function
o A pure virtual function is a "do nothing" function. Here "do nothing" means that it just provides
the template, and derived class implements the function.
o It can be considered as an empty function means that the pure virtual function does not have
any definition relative to the base class.
o Programmers need to redefine the pure virtual function in the derived class a s it has no
definition in the base class.
o A class having pure virtual function cannot be used to create direct objects of its own. It
means that the class is containing any pure virtual function then we cannot create the
object of that class. This type of class is known as an abstract class .
Syntax
There are two ways of creating a virtual function:

virtual void display() = 0;


or
virtual void display() {}
Let's understand through an example.
#include <iostream>
using namespace std;
// Abstract class
class Shape
{
public:
virtual float calculateArea() = 0; // pure virtual function.
};
class Square : public Shape
{
float a;
public:
Square(float l)
{
a = l;
}
float calculateArea()
{
return a*a;
}
};
class Circle : public Shape
{
float r;
public:
Circle(float x)
{
r = x;
}
float calculateArea()
{
return 3.14*r*r ;
}
};
class Rectangle : public Shape
{
float l;
float b;
public:
Rectangle(float x, float y)
{
l=x;
b=y;
}
float calculateArea()
{
return l*b;
}
};
int main()
{
Shape *shape;
Square s(3.4);
Rectangle r(5,6);
Circle c(7.8);
shape =&s;
int a1 =shape->calculateArea();
shape = &r;
int a2 = shape->calculateArea();
shape = &c;
int a3 = shape->calculateArea();
cout << "Area of the square is " <<a1<< endl;
cout << "Area of the rectangle is " <<a2<< endl;
cout << "Area of the circle is " <<a3<< endl;
return 0;
}
Differences between the virtual function and pure virtual function

Virtual function Pure virtual function


A virtual function is a member function in a base A pure virtual function is a member function in a base
class that can be redefined in a derived class. class whose declaration is provided in a base class and
implemented in a derived class.
The classes which are containing virtual The classes which are containing pure virtual function
functions are not abstract classes. are the abstract classes.
In case of a virtual function, definition of a In case of a pure virtual function, definition of a
function is provided in the base class. function is not provided in the base class.
The base class that contains a virtual function The base class that contains a pure virtual function
can be instantiated. becomes an abstract class, and that cannot be
instantiated.
If the derived class will not redefine the virtual If the derived class does not define the pure virtual
function of the base class, then there will be no function; it will not throw any error but the derived class
effect on the compilation. becomes an abstract class.
All the derived classes may or may not redefine All the derived classes must define the pure virtual
the virtual function. function.
#include <iostream>
class CMatrix {
public:
int matrix[2][2]; // Assuming a maximum size of 10x10
CMatrix () {
cout << "Enter elements of the matrix:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cin >> matrix[i][j];
}
}
}
void displayMatrix() {
cout << "Matrix:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
CMatrix addMatrix( CMatrix mat) {
CMatrix result;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result.matrix[i][j] = matrix[i][j] + mat.matrix[i][j];
}
}
return result;
}
};

int main() {
cout << "Enter elements for first matrix:" << endl;
CMatrix mat1;
cout << "Enter elements for second matrix:" << endl;
CMatrix mat2;
CMatrix sum = mat1.addMatrix(mat2);
cout << "Resultant matrix after addition:" << endl;
sum.displayMatrix();
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy