6 Virtual Function Polymorphism And Miscellaneous C Features

Object Oriented Programming · Unit 6 · 5 hrs

Virtual Function, Polymorphism, and miscellaneous C++ Features

Exam-focused notes for Virtual Function, Polymorphism, and miscellaneous C++ Features (Object Oriented Programming, CSC166): what the TU syllabus asks and how it has actually been tested, with 10 solved past questions from this unit.

Virtual Function, Polymorphism, and miscellaneous C++ Features in short

This unit completes C++'s runtime polymorphism: virtual functions and late binding, abstract classes built from pure virtual functions, virtual destructors and virtual base classes, friend and static functions, how assignment differs from copy initialization, the this pointer, and the difference between abstract and concrete classes.

Virtual Function, Polymorphism, and miscellaneous C++ Features: notes

Concept of Virtual functions

A virtual function is a member function declared in a base class with the keyword virtual and then redefined, or overridden, by a derived class using exactly the same signature; when it is called through a pointer or reference to the base class, C++ picks the actual function to run based on the real type of the object being pointed to, at run time, rather than on the declared type of the pointer.

#include <iostream>
using namespace std;

class Base {
public:
    virtual void print() { cout << "Print base class" << endl; }
    void show() { cout << "Show base class" << endl; }
};

class Derived : public Base {
public:
    void print() override { cout << "Print derived class" << endl; }
    void show() { cout << "Show derived class" << endl; }
};

int main() {
    Base *bptr;
    Derived d;
    bptr = &d;
    bptr->print();   // Print derived class (virtual, resolved at run time)
    bptr->show();     // Show base class (non-virtual, resolved at compile time)
    return 0;
}

Once a function is declared virtual in the base class, a derived class's own override is automatically treated as virtual too, even without repeating the virtual keyword.

Late Binding

Binding is the process of associating a function call with the actual code that runs for it. Early (static) binding happens at compile time: the compiler or linker fixes the function's address directly into the call, which is how ordinary function calls, function overloading and operator overloading are resolved. Late (dynamic) binding happens at run time: the program works out which function to call only when the call is reached, by checking the real type of the object involved; this is exactly what a virtual function provides, and it is the mechanism behind run time polymorphism.

Abstract class and pure virtual functions

Sometimes a base class cannot sensibly provide an implementation of a function at all, only its derived classes can, a Shape base class has no meaningful way to draw() itself in general. A pure virtual function declares such a function without any implementation, by writing = 0 in place of a function body:

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

A class that contains at least one pure virtual function is an abstract class: it can never be instantiated directly, and exists only to be inherited from, with each derived class supplying its own implementation of the pure virtual function.

What this unit covers

  • Concept of Virtual functions
  • Late Binding
  • Abstract class and pure virtual functions
  • Virtual Destructors
  • Virtual base class
  • Friend function and Static function
  • Assignment and copy initialization
  • Copy constructor
  • This pointer
  • Concrete classes
  • Polymorphism and its roles

Friend function and Static function

2080 · 5 marks

Explain about friend function and friend class with an example. [5]

A friend function is a function that is not a member of a class but has access to the private and protected members of that class. - The declaration is placed inside the class body (in either private or public section) preceded by the keyword friend - It is not a member function, so it is called ...

Open this answer on its own page →

2079 · 5 marks

Write short note on: a) Friend Function b) Early binding and late binding [5]

--- A friend function in C++ is a function that is not a member of a class but has the privilege to access the private and protected members of that class. It is declared inside the class using the keyword friend. - It is declared inside the class but defined outside the class scope. - It is not ...

Open this answer on its own page →

2078 · 5 marks

What is the concept of friend function? How it violates the data hiding principle? Justify with example. [5]

A friend function is a non-member function that is granted special access to the private and protected members of a class. Although it is not a member of the class, it can access all private and protected data of that class as if it were a member. The declaration of a friend function is made insi...

Open this answer on its own page →

Concept of Virtual functions

2080 · 5 marks

What is the use of reinterpret cast operator? Why do we need virtual function? [5]

Show solved answer

Reinterpret Cast Operator and Virtual Functions


Part 1: reinterpret_cast Operator

Definition

reinterpret_cast is a cast operator in C++ that converts one pointer type to another pointer type, even if the types are unrelated. It forces the compiler to treat the bit pattern of one type as if it were another type entirely.

As noted in the reference: "A cast operator is a special operator that forces one data type to be converted into another."

Syntax

reinterpret_cast<new_type>(expression);

Uses of reinterpret_cast

Use CaseDescription
Pointer to pointer conversionConvert int* to char* or any unrelated pointer type
Pointer to integer conversionStore a pointer value as an integer
Integer to pointer conversionConvert an integer back to a pointer
Low-level memory manipulationUsed in hardware/system programming

Example

#include <iostream>
using namespace std;

int main() {
    int a = 65;
    int* ptr = &a;

    // Reinterpret int pointer as char pointer
    char* cptr = reinterpret_cast<char*>(ptr);

    cout << "Integer value: " << *ptr << endl;
    cout << "Char interpretation: " << *cptr << endl;  // Output: A

    return 0;
}

Key Points

  • It does not check type safety; the programmer is responsible for correctness.
  • It is the most dangerous cast and should be used with caution.
  • Commonly used in low-level programming, such as device drivers or memory-mapped I/O.

Part 2: Why Do We Need Virtual Functions?

Problem Without Virtual Functions

When a base class pointer points to a derived class object, calling an overridden function without virtual will always call the base class version due to static (early) binding.

From the reference: "When a member function is not virtual, the function called is determined only by the type of the expression to the left of dot (.) or arrow (->) operator. This is called the static type."

What is a Virtual Function?

A virtual function is a member function declared in the base class using the keyword virtual, which tells the compiler to perform late binding (runtime binding) so that the correct overridden function is called based on the actual object type, not the pointer type.

From the reference: "Late Binding is achieved using Virtual functions."

Example Demonstrating the Need

#include <iostream>
using namespace std;

class Base {
public:
    virtual void print() {          // virtual function
        cout << "Print Base class" << endl;
    }
    void show() {                   // non-virtual function
        cout << "Show Base class" << endl;
    }
};

class Derived : public Base {
public:
    void print() {
        cout << "Print Derived class" << endl;
    }
    void show() {
        cout << "Show Derived class" << endl;
    }
};

int main() {
    Base* bptr;
    Derived d;
    bptr = &d;

    bptr->print();  // Virtual  -> calls Derived version (runtime binding)
    bptr->show();   // Non-virtual -> calls Base version (compile-time binding)

    return 0;
}

Output

Print Derived class
Show Base class

Why We Need Virtual Functions

  1. Runtime Polymorphism: Enables the correct function to be called based on the actual object at runtime, not the pointer type.
  2. Flexibility: A single base class pointer can manage objects of multiple derived classes and call appropriate methods.
  3. Extensibility: New derived classes can be added without changing existing code.
  4. Correct Overriding Behavior: Without virtual, overriding does not work as expected through base class pointers.

Important Note

From the reference: "If we have created a virtual function in the base class and it is being overridden in the derived class, then we don't need the virtual keyword in the derived class -- functions are automatically considered as virtual functions in the derived class."


Summary Table

Featurereinterpret_castVirtual Function
PurposeLow-level type conversionRuntime polymorphism
BindingN/ALate (runtime) binding
SafetyUnsafe, programmer's responsibilitySafe, resolved by vtable
Open this answer on its own page →

2080 · 5 marks

Explain the reason for member function overriding when using virtual function. [5]

Show solved answer

Member Function Overriding with Virtual Functions

Definition and Concept

Overriding means defining a member function with the same name in both the base class and the derived class. When such a function exists in both classes, the derived class function overrides the base class function.

Virtual function is a member function in the base class that is declared using the keyword virtual. When virtual functions are used, different functions can be executed by the same function call statement.


Reason for Member Function Overriding When Using Virtual Functions

The Core Problem (Without Virtual)

When a base class pointer is used to point to a derived class object, without virtual, the function call is resolved at compile time (static binding). This means the base class version of the function always gets called, even when the pointer is pointing to a derived class object. This defeats the purpose of inheritance and polymorphism.

How Virtual Solves It

When a function is declared virtual in the base class, the function call is resolved at runtime (dynamic binding). The function called is determined by the actual type of the object pointed to, not the type of the pointer.

As per the notes: "When a member function is virtual, the function called is determined by the actual most derived type of the object named by the expression left of the dot or pointed to by the expression left of the arrow. This is called the dynamic type."


Types of Polymorphism Involved

TypeHow AchievedBinding
Compile-time (Static)OverloadingAt compile time
Runtime (Dynamic)Overriding with virtualAt runtime

Example

#include <iostream>
using namespace std;

class base {
public:
    virtual void print() {          // virtual function
        cout << "Print base class" << endl;
    }
    void show() {                   // non-virtual function
        cout << "Show base class" << endl;
    }
};

class derived : public base {
public:
    void print() {                  // overrides base class print()
        cout << "Print derived class" << endl;
    }
    void show() {
        cout << "Show derived class" << endl;
    }
};

int main() {
    base *bptr;
    derived d;
    bptr = &d;          // base pointer pointing to derived object

    bptr->print();      // virtual function -> runtime binding
    bptr->show();       // non-virtual function -> compile-time binding
    return 0;
}

Output

Print derived class
Show base class

Explanation of Output

  • bptr->print() calls the derived class version because print() is declared virtual in the base class. The function is bound at runtime based on the actual object type (derived).
  • bptr->show() calls the base class version because show() is not virtual. It is bound at compile time based on the pointer type (base).

Key Points

  1. Runtime polymorphism is achieved only through a pointer or reference of a base class type.
  2. A base class pointer can point to objects of both base and derived classes.
  3. If a virtual function in the base class is overridden in the derived class, the virtual keyword is not required again in the derived class; the function is automatically considered virtual.
  4. Without virtual, member function overriding cannot achieve dynamic dispatch, making the concept of runtime polymorphism impossible.
Open this answer on its own page →

Abstract class and pure virtual functions

2080 · 5 marks

Differentiate between concrete class and abstract class. Define class template and function template with syntax. [5]

--- As stated in the notes: "There are two main types of classes: Abstract class and Concrete class. The main difference between the two arises from the level of implementation of their method functionalities." Feature Concrete Class Abstract Class --------- Definition A regular class where all m...

Open this answer on its own page →

Polymorphism and its roles

2076 · 10 marks

Explain types of polymorphism briefly. Write down roles of polymorphism. How can we achieve dynamic polymorphism briefly? Write down roles of polymorphism. How can we achieve dynamic polymorphism? Explain with example.[10]

Polymorphism means "one name, many forms." It allows the same function or operator to behave differently depending on the context. There are two main types: --- - The function to be called is determined at compile time. - Also called static binding or early binding. - Achieved through: - Function...

Open this answer on its own page →

2080.1 · 5 marks

Difference between compile time and run time polymorphism. [5]

Polymorphism means that the same thing or name exists in many forms to perform various actions. In C++, it is classified into two types: --- - Achieved using function overloading and operator overloading. - The compiler directly associates an address to the function call at compile time itself. -...

Open this answer on its own page →

This pointer

2076 · 5 marks

What is this pointer? How can we use it for name conflict resolution? Illustrate the use of multiple catch statement with example. [5]

--- The this pointer is an implicit (hidden) pointer available inside every non-static member function of a class. It automatically points to the object that invoked the member function. - Every object has access to its own address through the this pointer. - It is passed as a hidden argument to ...

Open this answer on its own page →

2080.1 · 5 marks

Write short notes on: a. This pointer b. ios member function [5]

--- In C++, this is a special implicit pointer that is automatically passed to every non-static member function of a class. It holds the address of the object that invokes the member function. - When a member function is called on an object, the compiler secretly passes a pointer to that object. ...

Open this answer on its own page →