[go: up one dir, main page]

0% found this document useful (0 votes)
33 views14 pages

OBJECT ORIENTED PROGRAMMING(Polymorphism)

OBJECT ORIENTED PROGRAMMING(Polymorphism

Uploaded by

Soumyo Sarkar
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)
33 views14 pages

OBJECT ORIENTED PROGRAMMING(Polymorphism)

OBJECT ORIENTED PROGRAMMING(Polymorphism

Uploaded by

Soumyo Sarkar
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/ 14

OBJECT ORIENTED PROGRAMMING

Polymorphism: Pointer to objects, pointer to derived class object, this pointer, run time and compile time
polymorphism, virtual functions, pure virtual functions, abstract class, virtual destructor.

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. Polymorphism is considered one of the
important features of Object-Oriented Programming.
Types of Polymorphism

 Compile-time Polymorphism
 Runtime Polymorphism

Compile time polymorphism: The overloaded functions 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. Now, let's consider the case where
function name and prototype is same.
Example:
class A // base class declaration.
{
int a;
public:
void display()
{
cout<< "Class A ";
}
};
class B : public A // derived class declaration.
{
int b;
public:
void display()
{
cout<<"Class B";
}
};

In the above case, the prototype of display() function is the same in both the base and derived class.
Therefore, the static binding cannot be applied. It would be great if the appropriate function is selected
at the run time. This is known as run time polymorphism.
Run time polymorphism: 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.
Example:
#include <iostream>
using namespace std;
class Animal {
public:
void eat(){
cout<<"Eating...";
}
};
class Dog: public Animal
{
public:
void eat()
{ cout<<"Eating bread...";
}
};
int main(void) {
Dog d = Dog();
d.eat();
return 0;
}

Output:
Eating bread...
Differences b/w compile time and run time polymorphism

Compile time polymorphism Run time polymorphism

The function to be invoked is known at the compile The function to be invoked is known at the run
time. time.

It is also known as overloading, early binding and It is also known as overriding, Dynamic
static binding. binding and late binding.

Overloading is a compile time polymorphism where Overriding is a run time polymorphism where
more than one method is having the same name but more than one method is having the same
with the different number of parameters or the type name, number of parameters and the type of
of the parameters. the parameters.

It is achieved by function overloading and operator It is achieved by virtual functions and pointers.
overloading.

It provides fast execution as it is known at the It provides slow execution as it is known at the
compile time. run time.

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

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
Pointer to object: A pointer to an object in C++ is a variable that holds the memory address of an object.
It allows indirect access to the object, providing a way to manipulate and interact with the object
dynamically. Pointers to objects are particularly useful when dealing with dynamically allocated memory,
enabling flexible memory management and dynamic object creation.

Advantages of Pointer to Object in C++


The advantages of using a pointer to an object in C++ are as follows:

 Pointers grant us the power to dynamically distribute storage, enabling object creation at execution
and releasing memory when it is not needed. It is especially useful in situations where either the
generation of objects is dependent on user input, or there are other runtime conditions, or when
knowledge of an object's size at compile time is lacking.
 When compared to passing by value, pointers allow us to pass objects to functions by reference,
which can be more effective. When we provide an object by value, a copy of the item is made, which
for large objects can be time and memory consuming. It is more effective to pass an object by
reference, which merely passes the item's address.
 Incorporating polymorphism into our coding is a viable option, as instances of derived classes can
be pointed to by including pointers from their base equivalents. As long as they share a base class,
we can develop code that interacts with objects of various sorts.
 Smart pointers offer ownership semantics for objects that are allocated dynamically. Objects'
lifespan can be governed using these tools to ensure they are properly disposed of when no longer
necessary. This guarantees accurate deallocation and prevents any unintended consequences from
the object's persistence.
Base Class Pointer for Derived Class Object in C++:

In C++, a pointer to a base type class object may point to an object of a derived class. This is conceivable
as a result of derived classes, which are classes that borrow characteristics from their base classes. It is
possible to employ both a reference pointing towards an object of either the base class or derived class as
they are compatible in type and offer several benefits. There exist diverse applications for working with
these pointers that belong to different classes.
Note: A base class pointer referring to a derived class is a pointer to a derived class, but it will retain its
aspect.
The pointer of the base class is endowed with the ability to modify its distinct functions and variables
while simultaneously being directed toward an object that originates from a subclass.

Program to show base class pointer pointing to a derived class object:


#include <iostream>
using namespace std;
class Shape {
public:
virtual void display() {
cout << "This is a shape." << endl;
}
};
class Rectangle: public Shape {
public:
void display() {
cout << "This is a rectangle." << endl;
}
};
class Circle: public Shape {
public:
void display() {
cout << "This is a circle." << endl;
}
};
int main() {
Shape* s; // Declare a base class pointer
Rectangle r; // Create a derived class object
Circle c; // Create another derived class object
s = &r; // Point the base class pointer to the rectangle object
s->display(); // Call the display() function of the derived class
s = &c; // Point the base class pointer to the circle object
s->display(); // Call the display() function of the derived class
return 0;
}

OUTPUT:
This is a rectangle.
This is a circle

Q. What is the difference between a pointer to an object and a reference to an object in C++?
Ans: In C++, one may find that a reference dwells as an alias to any given variable within existence, while
alternatively, a pointer takes shape as an object meant for storing memory addresses assigned to other
variables or objects. Although a reference has the ability to refer solely to one object, pointers have the
capability of concurrently pointing toward multiple objects.

‘this’ Pointer: In C++ programming, this is a keyword that refers to the current instance of the class.
There can be 3 main usage of this keyword in C++.

o It can be used to pass current object as a parameter to another method.


o It can be used to refer current class instance variable.
o It can be used to declare indexers.

Example
#include <iostream>
using namespace std;
class Employee {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Employee(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000); //creating an object of Employee
e1.display();
e2.display();
return 0;
}

Output:
101 Sonoo 890000
102 Nakul 59000

Virtual Functions: A virtual function is a member function in the base class that we expect to redefine
in derived classes.
Basically, a virtual function is used in the base class in order to ensure that the function is overridden.
This especially applies to cases where a pointer of base class points to an object of a derived class.
For example, consider the code below:
class Base {
public:
void print() {
// code
}
};
class Derived : public Base {
public:
void print() {
// code
}
};
Later, if we create a pointer of Base type to point to an object of Derived class and call the print()
function, it calls the print() function of the Base class.
In other words, the member function of Base is not overridden.
int main() {
Derived derived1;
Base* base1 = &derived1;
// calls function of Base class
base1->print();
return 0;
}
In order to avoid this, we declare the print() function of the Base class as virtual by using the virtual
keyword.
class Base {
public:
virtual void print() {
// code
}
};
Virtual functions are an integral part of polymorphism in C++. To learn more, check our tutorial on C++
Polymorphism.
Example 1: C++ virtual Function
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() {
cout << "Derived Function" << endl;
}
};
int main() {
Derved derived1;
// pointer of Base type that points to derived1
Base* base1 = &derived1;
// calls member function of Derived class
base1->print();
return 0;
}
Output
Derived Function

Pure Virtual Function


A virtual function is not used for performing any task. It only serves as a placeholder.
When the function has no definition, such function is known as "do-nothing" function.
The "do-nothing" function is known as a pure virtual function. A pure virtual function is a function
declared in the base class that has no definition relative to the base class.
A class containing the pure virtual function cannot be used to declare the objects of its own, such classes
are known as abstract base classes.
The main objective of the base class is to provide the traits to the derived classes and to create the base
pointer used for achieving the runtime polymorphism.
Pure virtual function can be defined as:
virtual void display() = 0;
Example:
#include <iostream>
using namespace std;
class Base
{
public:
virtual void show() = 0;
};
class Derived : public Base
{
public:
void show()
{
std::cout << "Derived class is derived from the base class." << std::endl;
}
};
int main()
{
Base *bptr;
//Base b;
Derived d;
bptr = &d;
bptr->show();
return 0;
}

Output:
Derived class is derived from the base class.
Advantages of Virtual Function
A virtual function provides the following advantages.

 Virtual functions provide the ability to create flexible and extensible code.
 Developers can add or remove features from existing objects, reducing maintenance costs and
improving overall flexibility by overriding a virtual function.
 It allows late binding, also known as run-time polymorphism.
 It can draw multiple shapes (e.g., circles, squares) on screen and treat them uniformly at the same
time by invoking their draw() methods via a single call-like shape->draw(). Without virtual
functions, it would require extra work for each shape type since the compiler wouldn’t know which
version of draw() should be called at compile time. Therefore, you need separate calls like circle-
>draw(), rectangle->draw(), etc.
Limitations of Virtual Functions
Some of the limitations of virtual functions are as follows:
 They are difficult to debug in a complex system because virtual functions make it challenging
to identify where the function is being called from.
 The function call slows down due to virtual mechanisms and makes it difficult for the compiler
to optimize because it does not know the location of the function at compile time.
 Virtual functions store virtual function tables for each class. This adds additional memory
overhead and increases the program’s memory footprint.
 Virtual function calls cannot be in-lined because they are resolved at runtime through the table.
 Virtual functions make the code more complex, making it difficult to understand the flow of
the program.

Differences between the virtual function and pure virtual function

Virtual function Pure virtual function

A virtual function is a member function in a A pure virtual function is a member function in a base
base class that can be redefined in a derived class whose declaration is provided in a base class
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 function; it will not throw any error but the derived
no effect on the compilation. class becomes an abstract class.

All the derived classes may or may not All the derived classes must define the pure virtual
redefine the virtual function. function.

Abstract Class
A class that contains a pure virtual function is known as an abstract class. In the above example, the
class Shape is an abstract class.
We cannot create objects of an abstract class. However, we can derive classes from them, and use their
data members and member functions (except pure virtual functions).
Example:
class Shape {
public:
// All the functions of both square and rectangle are clubbed together in a single class.
void width(int w) {
shape_width = w;
}
void height(int h) {
shape_height = h;
}
int areaOfSquare(int s) {
return 4 * s;
}
int areaOfRectange(int l, int b) {
return (l * b);
}
protected:
int shape_width;
int shape_height;
};
int main (){
shapes R;
R.width(5);
R.height(10);
cout<<"The area of rectangle is"<<R.areaOfRectangle";
return 0;
}

What are the restrictions to abstract class?


The following uses of abstract classes are not permitted:
 Conversions made consciously

 Member data or variables

 Types of function output

 Forms of debate


Virtual Destructor
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results
in undefined behavior. To correct this situation, the base class should be defined with a virtual
destructor.
For example, the following program results in undefined behavior.
#include <iostream>
using namespace std;
class base {
public:
base()
{ cout << "Constructing base\n"; }
~base()
{ cout<< "Destructing base\n"; }
};
class derived: public base {
public:
derived()
{ cout << "Constructing derived\n"; }
~derived()
{
cout << "Destructing derived\n";
}
};

int main()
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
Output
Constructing base
Constructing derived
Destructing base

MCQ Type: Polymorphism - Object Oriented Programming Questions and Answers - Sanfoundry

MCQ Type: Polymorphism Mcqs In Object Oriented Programming(OOP) | T4Tutorials.com

Broad Type: CPP Programming Polymorphism based Questions Answers - EXAMRADAR

You might also like