0% found this document useful (0 votes)
2 views8 pages

Polymorphism

Polymorphism in Object-Oriented Programming allows objects to be treated as instances of their base class, enabling a single action to take different forms. It includes Compile-Time Polymorphism (function and operator overloading) and Run-Time Polymorphism (using virtual functions and abstract classes). Abstract classes cannot be instantiated and require derived classes to implement pure virtual functions, promoting interface design, polymorphism, and code reusability.

Uploaded by

Muzzamil Rani
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)
2 views8 pages

Polymorphism

Polymorphism in Object-Oriented Programming allows objects to be treated as instances of their base class, enabling a single action to take different forms. It includes Compile-Time Polymorphism (function and operator overloading) and Run-Time Polymorphism (using virtual functions and abstract classes). Abstract classes cannot be instantiated and require derived classes to implement pure virtual functions, promoting interface design, polymorphism, and code reusability.

Uploaded by

Muzzamil Rani
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/ 8

Polymorphism is a core concept in Object-Oriented Programming (OOP) that allows objects

to be treated as instances of their base class rather than their actual class. It provides a way to
perform a single action in different forms. There are mainly two types of polymorphism:

1. Compile-Time Polymorphism (also known as Static Polymorphism):


○ Function Overloading: Allows multiple functions with the same name but
different parameters.
○ Operator Overloading: Allows operators to be redefined to work with
user-defined types.
2. Run-Time Polymorphism (also known as Dynamic Polymorphism):
○ Virtual Functions: Allows functions to be overridden in derived classes. It is
resolved at runtime based on the type of the object pointed to by a base class
pointer.

1. Compile-Time Polymorphism

Function Overloading

#include <iostream>
using namespace std;

class Display {
public:
// Overloaded function to display an integer
void show(int i) {
cout << "Integer: " << i << endl;
}

// Overloaded function to display a double


void show(double d) {
cout << "Double: " << d << endl;
}

// Overloaded function to display a string


void show(const string& s) {
cout << "String: " << s << endl;
}
};

int main() {
Display d;
d.show(42); // Calls show(int)
d.show(3.14); // Calls show(double)
d.show("Hello!"); // Calls show(string)

return 0;
}

Operator Overloading

#include <iostream>
using namespace std;

class Complex {
private:
float real;
float imag;

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

// Overload the + operator


Complex operator + (const Complex& obj) {
return Complex(real + obj.real, imag + obj.imag);
}

void display() {
cout << "Real: " << real << " Imaginary: " << imag << endl;
}
};

int main() {
Complex c1(3.5, 2.5), c2(1.5, 3.5);
Complex c3 = c1 + c2; // Calls operator+
c3.display();

return 0;
}

2. Run-Time Polymorphism

Virtual Functions

Run-time polymorphism is achieved using virtual functions and inheritance. The function call is
resolved at runtime based on the actual object type.

#include <iostream>
using namespace std;

// Base class
class Base {
public:
virtual void display() { // Virtual function
cout << "Display from Base" << endl;
}

virtual ~Base() {} // Virtual destructor


};

// Derived class
class Derived : public Base {
public:
void display() override { // Overriding the base class function
cout << "Display from Derived" << endl;
}
};

int main() {
Base* basePtr;
Derived derivedObj;
basePtr = &derivedObj;

// Calls the Derived class's display() function


basePtr.display();

return 0;
}

Pure Virtual Functions

Pure virtual functions are a special kind of virtual function that do not have an implementation
in the base class. They are used to create abstract classes that cannot be instantiated directly.
Derived classes must provide an implementation for pure virtual functions.

Characteristics of Pure Virtual Functions:

1. Abstract Class: A class with at least one pure virtual function is called an abstract class.
2. No Instantiation: You cannot create objects of an abstract class.
3. Derived Classes: Derived classes must override all pure virtual functions to be
instantiated.

Syntax:

● To declare a pure virtual function, use = 0 in the function declaration.

Example:

#include <iostream>
using namespace std;

class AbstractBase {
public:
// Pure virtual function
virtual void display() = 0;

};
class ConcreteDerived : public AbstractBase {
public:
void display() override { // Providing implementation
cout << "ConcreteDerived display function" << endl;
}
};

int main() {
// AbstractBase ab; // Error: cannot instantiate abstract class
ConcreteDerived cd;
cd.display(); // Outputs: "ConcreteDerived display function"

return 0;
}

Abstract Classes

An abstract class in C++ is a class that cannot be instantiated directly and


is designed to be a base class for other classes. It is used to define a
common interface for derived classes, which must implement specific
behaviors. An abstract class contains at least one pure virtual
function—a function with no implementation in the base class, forcing
derived classes to provide their own implementation.

Characteristics

Cannot be Instantiated: You cannot create objects of an abstract class. It


serves as a blueprint for derived classes.
Pure Virtual Functions: An abstract class contains one or more pure virtual functions. A pure
virtual function is declared by assigning = 0 in the function declaration. These functions are
intended to be overridden in derived classes.
cpp
virtual void someFunction() = 0;

1. Forcing Derived Classes to Implement Functions: Derived classes must provide


concrete implementations for all pure virtual functions of the abstract class. If a derived
class does not override all the pure virtual functions, it will also be treated as an abstract
class and cannot be instantiated.
2. Polymorphism: Abstract classes are used to support polymorphism, where a base
class pointer can point to objects of derived classes and call their implementations of the
pure virtual functions.

Syntax of Abstract Class


#include <iostream>
using namespace std;

// Abstract class (contains at least one pure virtual function)


class Shape {
public:
// Pure virtual function
virtual void draw() = 0;

// Regular member function


void description() {
cout << "This is a shape." << endl;
}
};

// Derived class that inherits from Shape


class Circle : public Shape {
public:
// Implementing the pure virtual function
void draw() override {
cout << "Drawing a circle." << endl;
}
};

// Derived class that inherits from Shape


class Square : public Shape {
public:
// Implementing the pure virtual function
void draw() override {
cout << "Drawing a square." << endl;
}
};

int main() {
// Cannot create an object of an abstract class
// Shape shape; // Error

// Using polymorphism
Shape* shape1 = new Circle();
Shape* shape2 = new Square();

shape1.draw(); // Calls Circle's implementation


shape2.draw(); // Calls Square's implementation

shape1.description(); // Calls base class function


shape2.description(); // Calls base class function

delete shape1;
delete shape2;

return 0;
}

Explanation of the Example

● Abstract Class (Shape): The Shape class has a pure virtual function draw(), making it
an abstract class. It also contains a regular member function description(), which is
available to any derived class.
● Derived Classes (Circle and Square): These classes inherit from Shape and provide
their own implementations of the draw() function. Since they implement the pure virtual
function, objects of these classes can be created.
● Polymorphism: A base class pointer (Shape*) is used to point to derived class objects.
This enables the use of the draw() function through the base class pointer, which calls
the appropriate version of the function based on the object type (Circle or Square).
Why Use Abstract Classes?

1. Interface Design: Abstract classes are used to create interfaces that other classes must
follow. It defines the required functions without specifying how they should be
implemented, allowing each derived class to provide its own behavior.
2. Polymorphism: Abstract classes allow for polymorphic behavior, where a base class
pointer or reference can be used to invoke methods from derived classes, even though
the exact type of the object is determined at runtime.
3. Code Reusability: Common code can be placed in the abstract class, and different
derived classes can share this code. Only the specific implementations of pure virtual
functions need to be provided by derived classes.
4. Enforcing a Contract: Abstract classes ensure that all derived classes implement
certain methods, thereby enforcing a contract that must be followed by all subclasses.

Pure Virtual Functions vs Virtual Functions

● A virtual function is a function that can be overridden in a derived class but still has a
default implementation in the base class.
● A pure virtual function has no implementation in the base class and must be
overridden in the derived class. It is used to make a class abstract.

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