8 Static And Dynamic Polymorphism

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.

Static and Dynamic Polymorphism: notes

Static polymorphism: function overloading

Static polymorphism (compile-time polymorphism) is when the function to call is decided during compilation. Function overloading is one form. Many functions share a name but differ in their parameters.

class Print {
public:
    void show(int a)    { cout << "int " << a << endl; }
    void show(double a) { cout << "double " << a << endl; }
    void show(string a) { cout << "string " << a << endl; }
};
int main() {
    Print p;
    p.show(5);
    p.show(2.5);
    p.show("hi");
}

The compiler matches the call to the right version by looking at the arguments. This is also called early binding.

Static polymorphism: operator overloading

Operator overloading is the second form of static polymorphism. The same operator gives different results for different operand types. For example + adds numbers, joins strings and can add two Complex objects.

class Money {
    int amt;
public:
    Money(int a = 0) { amt = a; }
    Money operator+(Money m) { return Money(amt + m.amt); }
};

The compiler picks the correct meaning from the operand types before the program runs.

Dynamic polymorphism definition

Dynamic polymorphism (run-time polymorphism) means the function to call is chosen while the program runs. It uses inheritance, function overriding, virtual functions and a base class pointer or reference.

A base pointer can point to a derived object. With a virtual function, the call goes to the version of the actual object, not the pointer type.

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]

--- Feature Early Binding (Static Binding) Late Binding (Dynamic Binding) --------- Time of Resolution Resolved at compile time Resolved at run time Mechanism Uses normal functions / function overloading Uses virtual functions Flexibility Less flexible More flexible Speed Faster execution Slightl...

Open this answer on its own page →

2078 · 5 marks

How-late binding differs from early binding? How can you achieve dynamic polymorphism? Explain with example. [5]

Show solved 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

FeatureEarly BindingLate Binding
Resolution timeCompile timeRun time
MechanismOverloadingVirtual functions
FlexibilityLess flexibleMore flexible
SpeedFasterSlightly slower
Polymorphism typeStaticDynamic

Dynamic Polymorphism

Dynamic polymorphism is achieved in C++ by:

  1. Declaring a function as virtual in the base class
  2. Overriding that function in derived classes
  3. 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

  • ptr is a pointer of type Shape*
  • At compile time, the compiler cannot determine which draw() to call
  • At run time, the actual object (Circle or Rectangle) determines which version of draw() executes
  • This is late binding in action, enabling dynamic polymorphism

Note: Without the virtual keyword, early binding would occur and Shape::draw() would always be called regardless of the actual object type.

Open this answer on its own page →

0 · 5 marks

How late binding differs from early binding? How can you achieve dynamic polymorphism? Explain with example. [5]

Show solved 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

FeatureEarly BindingLate Binding
Resolution timeCompile timeRun time
MechanismOverloadingVirtual functions
FlexibilityLess flexibleMore flexible
SpeedFasterSlightly slower
Polymorphism typeStaticDynamic

Dynamic Polymorphism

Dynamic polymorphism is achieved in C++ by:

  1. Declaring a function as virtual in the base class
  2. Overriding that function in derived classes
  3. 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 ptr behaves differently depending on the object it points to.

Note: The virtual keyword instructs the compiler to use a vtable (virtual table) mechanism to resolve function calls at run time.

Open this answer on its own page →

Abstract classes and concrete classes

2082 · 5 marks

What is the difference between abstract class and concrete class? Explain with example. [5]

Show solved 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

FeatureAbstract classConcrete class
InstantiationNot possible, only pointers and referencesObjects can be created directly
FunctionsHas at least one pure virtual (= 0)Every function has a body
How it is declaredNo keyword, the = 0 on a virtual marks itNothing special is written
PurposeDefines an interface or a common templateProvides a usable, complete type
DestructorShould be declared virtualVirtual 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.

Open this answer on its own page →

2081 · 5 marks

Distinguish between concrete class and abstract class. Describe the roles of polymorphism. [5]

Feature Concrete class Abstract class --------- Definition Every member function it declares or inherits has a body It declares at least one pure virtual function, written virtual T f() = 0; Instantiation Objects can be created directly No object can be created, only pointers and references to it...

Open this answer on its own page →

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]

(a) Difference Between Abstract Class and Concrete Class Feature Abstract Class Concrete Class --------- Definition A class that cannot be instantiated directly and may contain pure virtual functions A class that can be instantiated directly and provides implementation for all its methods Instant...

Open this answer on its own page →

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 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

TypeAlso Known AsResolved At
Compile-time PolymorphismStatic / Early BindingCompile time
Run-time PolymorphismDynamic / Late BindingRun 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 virtual in 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

ConceptWhere Used
virtual keywordDeclared in Employee::CalculateSalary()
override keywordUsed in both derived classes (C++11)
Dynamic DispatchBase class pointer empPtr calls correct version at run time
Open this answer on its own page →

2080.1 · 5 marks

Differentiate between virtual function and pure virtual function with an example. [5]

A virtual function is a member function declared in a base class using the virtual keyword that can be overridden in derived classes. It has a definition (body) in the base class, so objects of the base class can still be instantiated and the function can be called directly. Key characteristics: ...

Open this answer on its own page →

Function overriding

2080 · 5 marks

Differentiate between function overloading and function overriding in C++. [5]

--- Function overloading means defining multiple functions with the same name but with different parameter lists (different number, type, or order of parameters) within the same class or scope. - Resolved at compile time (Static/Early Binding) - Occurs in the same class - Return type alone cannot...

Open this answer on its own page →

Pure virtual functions

2079 · 5 marks

Explain the use of pure virtual function with example. [5]

A pure virtual function is a virtual function that has no implementation in the base class and is declared by assigning = 0 in its declaration. A class containing at least one pure virtual function is called an Abstract Class. --- Feature Description ------ Declaration Uses = 0 at the end Base cl...

Open this answer on its own page →

2078 · 5 marks

Explain pure virtual functions with example. [5]

A pure virtual function is a virtual function that has no implementation in the base class and is declared by assigning = 0 in its declaration. It forces every derived class to provide its own implementation of that function. Syntax: --- Feature Description ------ Declaration Uses = 0 at the end ...

Open this answer on its own page →

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]

(a) Ways of Achieving Static Polymorphism Static Polymorphism (also called compile-time polymorphism) is the mechanism where the decision about which function or operator to call is made at compile time rather than at runtime. It is achieved through the following ways: --- Defining multiple funct...

Open this answer on its own page →