Object Oriented Programming · Unit 8
Static and Dynamic Polymorphism
Exam-focused notes for Static and Dynamic Polymorphism (Object Oriented Programming, BIT153): what the TU syllabus asks and how it has actually been tested, with 12 solved past questions from this unit.
Static and Dynamic Polymorphism in short
Polymorphism means "many forms". C++ supports it at compile time (static) and at run time (dynamic). This chapter shows both and explains virtual functions and abstract classes.
What this unit covers
- Static polymorphism: function overloading
- Static polymorphism: operator overloading
- Dynamic polymorphism definition
- Virtual functions
- Pure virtual functions
- Abstract classes and concrete classes
- Early binding versus late binding
- Function overriding
Early binding versus late binding
2082 · 5 marks
Differentiate between early binding and late binding. Write a program to show dynamic polymorphism using virtual function. [2+3]
2078 · 5 marks
How-late binding differs from early binding? How can you achieve dynamic polymorphism? Explain with example. [5]
Show solved answerHide answer
Late Binding vs Early Binding and Dynamic Polymorphism
Early Binding (Static Binding)
Early binding means the compiler resolves the function call at compile time. The decision of which function to call is made before the program runs.
- Also called compile-time binding or static polymorphism
- Examples: function overloading, operator overloading
- Faster execution since binding is done at compile time
Late Binding (Dynamic Binding)
Late binding means the function call is resolved at run time, not at compile time. The decision of which function to execute depends on the actual object type during execution.
- Also called run-time binding or dynamic polymorphism
- Achieved using virtual functions and pointers/references to base class
- Slightly slower due to run-time lookup (via vtable), but provides flexibility
Key Differences
| Feature | Early Binding | Late Binding |
|---|---|---|
| Resolution time | Compile time | Run time |
| Mechanism | Overloading | Virtual functions |
| Flexibility | Less flexible | More flexible |
| Speed | Faster | Slightly slower |
| Polymorphism type | Static | Dynamic |
Dynamic Polymorphism
Dynamic polymorphism is achieved in C++ by:
- Declaring a function as
virtualin the base class - Overriding that function in derived classes
- Using a base class pointer or reference to call the function
Example
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() { // virtual function -> late binding
cout << "Drawing Shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override { // overriding in derived class
cout << "Drawing Circle" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() override { // overriding in derived class
cout << "Drawing Rectangle" << endl;
}
};
int main() {
Shape *ptr; // base class pointer
Circle c;
Rectangle r;
ptr = &c;
ptr->draw(); // Output: Drawing Circle (resolved at run time)
ptr = &r;
ptr->draw(); // Output: Drawing Rectangle (resolved at run time)
return 0;
}
Output
Drawing Circle
Drawing Rectangle
Explanation
ptris a pointer of typeShape*- At compile time, the compiler cannot determine which
draw()to call - At run time, the actual object (
CircleorRectangle) determines which version ofdraw()executes - This is late binding in action, enabling dynamic polymorphism
Note: Without the
virtualkeyword, early binding would occur andShape::draw()would always be called regardless of the actual object type.
0 · 5 marks
How late binding differs from early binding? How can you achieve dynamic polymorphism? Explain with example. [5]
Show solved answerHide answer
Late Binding vs Early Binding and Dynamic Polymorphism
Early Binding (Static Binding)
Early binding means the compiler resolves the function call at compile time. The decision of which function to call is made before the program runs.
- Also called compile-time binding or static polymorphism
- Examples: function overloading, operator overloading
- Faster execution since binding is done at compile time
Late Binding (Dynamic Binding)
Late binding means the function call is resolved at run time, not at compile time. The decision of which function to execute depends on the actual object type during execution.
- Also called run-time binding or dynamic polymorphism
- Achieved using virtual functions and pointers/references to base class
- Slightly slower due to run-time overhead (vtable lookup)
Key Differences
| Feature | Early Binding | Late Binding |
|---|---|---|
| Resolution time | Compile time | Run time |
| Mechanism | Overloading | Virtual functions |
| Flexibility | Less flexible | More flexible |
| Speed | Faster | Slightly slower |
| Polymorphism type | Static | Dynamic |
Dynamic Polymorphism
Dynamic polymorphism is achieved in C++ by:
- Declaring a function as
virtualin the base class - Overriding that function in derived classes
- Using a base class pointer or reference to call the function
Example
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() { // virtual function -> late binding
cout << "Drawing Shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() { // overrides base class function
cout << "Drawing Circle" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() { // overrides base class function
cout << "Drawing Rectangle" << endl;
}
};
int main() {
Shape *ptr; // base class pointer
Circle c;
Rectangle r;
ptr = &c;
ptr->draw(); // calls Circle::draw() at run time
ptr = &r;
ptr->draw(); // calls Rectangle::draw() at run time
return 0;
}
Output
Drawing Circle
Drawing Rectangle
Explanation
- Without
virtual, both calls would print"Drawing Shape"(early binding). - With
virtual, the correct overridden function is called based on the actual object pointed to at run time (late binding). - This is dynamic polymorphism: the same pointer
ptrbehaves differently depending on the object it points to.
Note: The
virtualkeyword instructs the compiler to use a vtable (virtual table) mechanism to resolve function calls at run time.
Abstract classes and concrete classes
2082 · 5 marks
What is the difference between abstract class and concrete class? Explain with example. [5]
Show solved answerHide answer
Abstract Class and Concrete Class in C++
What makes a class abstract in C++
C++ has no abstract keyword. A class becomes abstract the moment it declares at least one pure virtual function, written by putting = 0 after a virtual member function instead of a body:
virtual double area() const = 0; // pure virtual, so the class is abstract
An abstract class cannot be instantiated. The compiler refuses Shape s; with "cannot declare variable of abstract type". It can still be used as a base type: pointers and references of the abstract type are perfectly legal, and they are exactly how runtime polymorphism is obtained.
Because objects are usually deleted through a base pointer, an abstract base class should also declare a virtual destructor, otherwise the derived part of the object is never destroyed.
Key characteristics:
- At least one member function is declared pure virtual with
= 0. - No object of the class can be created, though base pointers and references are allowed.
- It may also contain ordinary data members and fully implemented member functions.
- A derived class stays abstract until it overrides every pure virtual it inherits.
What a concrete class is
A concrete class supplies a body for every function it declares or inherits, so nothing is left unimplemented. It can be instantiated directly, and it is the only kind of class from which real objects are made. A concrete class is very often a class derived from an abstract base that has filled in the missing implementations.
Key characteristics:
- Every inherited pure virtual function has been overridden.
- Objects can be created on the stack, with
new, or inside a container. - It may be a standalone class or the leaf of an inheritance hierarchy.
Comparison
| Feature | Abstract class | Concrete class |
|---|---|---|
| Instantiation | Not possible, only pointers and references | Objects can be created directly |
| Functions | Has at least one pure virtual (= 0) | Every function has a body |
| How it is declared | No keyword, the = 0 on a virtual marks it | Nothing special is written |
| Purpose | Defines an interface or a common template | Provides a usable, complete type |
| Destructor | Should be declared virtual | Virtual only if it is itself a base |
In Java the same idea is written with the abstract keyword on the class and on the method; in C++ the = 0 on a virtual function carries that meaning by itself.
Worked example
#include <iostream>
#include <string>
// Abstract class: it declares a pure virtual function, so no Shape object can exist.
class Shape {
protected:
std::string color;
public:
explicit Shape(const std::string& c) : color(c) {}
virtual ~Shape() = default; // virtual destructor for safe deletion via a base pointer
virtual double area() const = 0; // pure virtual: this is what makes Shape abstract
void displayColor() const { // an ordinary member, already implemented
std::cout << "Color: " << color << "\n";
}
};
// Concrete class: it gives a body to the inherited pure virtual function.
class Circle : public Shape {
double radius;
public:
Circle(double r, const std::string& c) : Shape(c), radius(r) {}
double area() const override { return 3.14159 * radius * radius; }
};
// Another concrete class from the same abstract base.
class Rectangle : public Shape {
double length, width;
public:
Rectangle(double l, double w, const std::string& c)
: Shape(c), length(l), width(w) {}
double area() const override { return length * width; }
};
int main() {
// Shape s("Red"); // compile error: cannot declare variable of abstract type Shape
Circle c(5.0, "Red");
c.displayColor();
std::cout << "Circle area: " << c.area() << "\n";
Rectangle r(4.0, 6.0, "Blue");
r.displayColor();
std::cout << "Rectangle area: " << r.area() << "\n";
const Shape& s = c; // a reference to the abstract type is legal and dispatches virtually
std::cout << "Through base reference: " << s.area() << "\n";
return 0;
}
Output:
Color: Red
Circle area: 78.5398
Color: Blue
Rectangle area: 24
Through base reference: 78.5398
Here Shape is the abstract class. It fixes the interface every shape must offer, area(), without deciding how any particular shape computes it, and it supplies one ready made service, displayColor(). Circle and Rectangle are the concrete classes: each overrides area(), so each can be instantiated. The commented out line shows the practical difference, since only the concrete types produce objects while the abstract type produces the common contract they all obey.
2081 · 5 marks
Distinguish between concrete class and abstract class. Describe the roles of polymorphism. [5]
2079 · 10 marks
Differentiate between abstract class and concrete class.Write a program to create a class named 'Quadratic' that represents a function of the form f(x) = ax + bx +C, where x is a real variable and a, b, c are real constants. The class must satisfy the following requirements: a. A constructor should be provided that takes the values of a, b and c as arguments. All three of these arguments should default to zero. b. A function that takes a single argument x return the value of f(x). c. All data members should be private.[2+8]
Virtual functions
2080 · 10 marks
What is Polymorphism in Object Oriented Programming? Implement a class Employee with a virtual function CalculateSalary() that returns the salary of the employee. Create two derived classes HourlyEmployee and SalariedEmployee. Override the CalculateSalary() function in both derived classes to calculate the salary of an hourly employee and a salaried employee respectively. Write a program that creates objects of both derived classes and calls the CalculateSalary() function for each.[10]
Show solved answerHide answer
Polymorphism in OOP and Virtual Function Implementation
What is Polymorphism?
Polymorphism is one of the four fundamental pillars of Object Oriented Programming (along with Encapsulation, Inheritance, and Abstraction). The word polymorphism comes from Greek meaning "many forms".
In OOP, polymorphism means the ability of a single interface (function name or operator) to behave differently depending on the object that invokes it.
Types of Polymorphism
| Type | Also Known As | Resolved At |
|---|---|---|
| Compile-time Polymorphism | Static / Early Binding | Compile time |
| Run-time Polymorphism | Dynamic / Late Binding | Run time |
- Compile-time polymorphism is achieved through function overloading and operator overloading.
- Run-time polymorphism is achieved through virtual functions and function overriding (inheritance).
Key Concepts for Run-time Polymorphism
- Virtual Function: A function declared with the keyword
virtualin the base class. It tells the compiler to resolve the function call at run time based on the actual object type, not the pointer/reference type. - Override: Redefining a virtual function in a derived class with the same signature.
- Base class pointer can point to derived class objects, and the correct overridden function is called automatically (dynamic dispatch).
C++ Program Implementation
#include <iostream>
using namespace std;
// -----------------------------------------------
// Base Class: Employee
// -----------------------------------------------
class Employee {
protected:
string name;
public:
// Constructor
Employee(string empName) {
name = empName;
}
// Virtual function to be overridden in derived classes
virtual double CalculateSalary() {
return 0.0;
}
// Virtual display function
virtual void display() {
cout << "Employee Name : " << name << endl;
cout << "Salary : Rs. " << CalculateSalary() << endl;
}
// Virtual destructor (good practice with virtual functions)
virtual ~Employee() {}
};
// -----------------------------------------------
// Derived Class 1: HourlyEmployee
// Salary = hoursWorked * hourlyRate
// -----------------------------------------------
class HourlyEmployee : public Employee {
private:
double hoursWorked;
double hourlyRate;
public:
// Constructor
HourlyEmployee(string empName, double hours, double rate)
: Employee(empName) {
hoursWorked = hours;
hourlyRate = rate;
}
// Override CalculateSalary()
double CalculateSalary() override {
return hoursWorked * hourlyRate;
}
void display() override {
cout << "----- Hourly Employee -----" << endl;
cout << "Employee Name : " << name << endl;
cout << "Hours Worked : " << hoursWorked << endl;
cout << "Hourly Rate : Rs. " << hourlyRate << endl;
cout << "Total Salary : Rs. " << CalculateSalary() << endl;
}
};
// -----------------------------------------------
// Derived Class 2: SalariedEmployee
// Salary = fixedMonthlySalary (fixed, no calculation needed)
// -----------------------------------------------
class SalariedEmployee : public Employee {
private:
double monthlySalary;
public:
// Constructor
SalariedEmployee(string empName, double salary)
: Employee(empName) {
monthlySalary = salary;
}
// Override CalculateSalary()
double CalculateSalary() override {
return monthlySalary;
}
void display() override {
cout << "----- Salaried Employee -----" << endl;
cout << "Employee Name : " << name << endl;
cout << "Monthly Salary : Rs. " << CalculateSalary() << endl;
}
};
// -----------------------------------------------
// Main Function
// -----------------------------------------------
int main() {
// Create objects of derived classes
HourlyEmployee emp1("Ram Sharma", 160, 150.0); // 160 hrs, Rs.150/hr
SalariedEmployee emp2("Sita Thapa", 55000.0); // Fixed Rs.55000/month
// Call display (which internally calls CalculateSalary)
emp1.display();
cout << endl;
emp2.display();
cout << endl;
// Demonstrating Run-time Polymorphism using Base class pointer
cout << "=== Run-time Polymorphism Demo ===" << endl;
Employee* empPtr; // Base class pointer
empPtr = &emp1; // Points to HourlyEmployee object
cout << "Salary (via base pointer): Rs. " << empPtr->CalculateSalary() << endl;
empPtr = &emp2; // Points to SalariedEmployee object
cout << "Salary (via base pointer): Rs. " << empPtr->CalculateSalary() << endl;
return 0;
}
Expected Output
----- Hourly Employee -----
Employee Name : Ram Sharma
Hours Worked : 160
Hourly Rate : Rs. 150
Total Salary : Rs. 24000
----- Salaried Employee -----
Employee Name : Sita Thapa
Monthly Salary : Rs. 55000
=== Run-time Polymorphism Demo ===
Salary (via base pointer): Rs. 24000
Salary (via base pointer): Rs. 55000
Explanation of Key Points
| Concept | Where Used |
|---|---|
virtual keyword | Declared in Employee::CalculateSalary() |
override keyword | Used in both derived classes (C++11) |
| Dynamic Dispatch | Base class pointer empPtr calls correct version at run time |
2080.1 · 5 marks
Differentiate between virtual function and pure virtual function with an example. [5]
Function overriding
2080 · 5 marks
Differentiate between function overloading and function overriding in C++. [5]
Pure virtual functions
2079 · 5 marks
Explain the use of pure virtual function with example. [5]
Static polymorphism
0 · 10 marks
What are the different ways of achieving static polymorphism?Discuss overloading of pre-increment and post-increment operators with suitable examples.[5+5]
Make Unit 8 stick
Practice BIT153 with flashcards & quizzes