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.
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]
2079 · 5 marks
Write short note on: a) Friend Function b) Early binding and late binding [5]
2078 · 5 marks
What is the concept of friend function? How it violates the data hiding principle? Justify with example. [5]
Concept of Virtual functions
2080 · 5 marks
What is the use of reinterpret cast operator? Why do we need virtual function? [5]
Show solved answerHide 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 Case | Description |
|---|---|
| Pointer to pointer conversion | Convert int* to char* or any unrelated pointer type |
| Pointer to integer conversion | Store a pointer value as an integer |
| Integer to pointer conversion | Convert an integer back to a pointer |
| Low-level memory manipulation | Used 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
- Runtime Polymorphism: Enables the correct function to be called based on the actual object at runtime, not the pointer type.
- Flexibility: A single base class pointer can manage objects of multiple derived classes and call appropriate methods.
- Extensibility: New derived classes can be added without changing existing code.
- 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
| Feature | reinterpret_cast | Virtual Function |
|---|---|---|
| Purpose | Low-level type conversion | Runtime polymorphism |
| Binding | N/A | Late (runtime) binding |
| Safety | Unsafe, programmer's responsibility | Safe, resolved by vtable |
2080 · 5 marks
Explain the reason for member function overriding when using virtual function. [5]
Show solved answerHide 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
| Type | How Achieved | Binding |
|---|---|---|
| Compile-time (Static) | Overloading | At compile time |
| Runtime (Dynamic) | Overriding with virtual | At 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 becauseprint()is declaredvirtualin the base class. The function is bound at runtime based on the actual object type (derived).bptr->show()calls the base class version becauseshow()is not virtual. It is bound at compile time based on the pointer type (base).
Key Points
- Runtime polymorphism is achieved only through a pointer or reference of a base class type.
- A base class pointer can point to objects of both base and derived classes.
- If a virtual function in the base class is overridden in the derived class, the
virtualkeyword is not required again in the derived class; the function is automatically considered virtual. - Without
virtual, member function overriding cannot achieve dynamic dispatch, making the concept of runtime polymorphism impossible.
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]
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]
2080.1 · 5 marks
Difference between compile time and run time polymorphism. [5]
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]
2080.1 · 5 marks
Write short notes on: a. This pointer b. ios member function [5]
Make Unit 6 stick
Practice CSC166 with flashcards & quizzes