2080 8

CSC166 ยท 2080 ยท 5 marks

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

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

Object Oriented ProgrammingChapter 6: Virtual Function, Polymorphism, and miscellaneous C++ FeaturesConcept of Virtual functions

Quick answer

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.

Reinterpret Cast Operator and Virtual Functions


Part 1: reinterpret_cast Operator

Definition

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

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.