Virtual Class in C++

 Virtual Class 

A virtual class usually refers to a class that contains at least one virtual function.
Virtual functions enable runtime polymorphism, meaning the function call is resolved at runtime, not at compile time.

Virtual classes are mainly used in inheritance to achieve dynamic binding.

  • Function calls are decided at runtime
  • Base class pointer calls the derived version of the function

This gives flexibility
Supports object-oriented design

Key Concepts Related to Virtual Class

Term

Meaning

Virtual Function

A member function declared using the virtual keyword

Runtime Polymorphism

Function call resolved at runtime

Base Class Pointer

Pointer of base class pointing to derived object

Dynamic Binding

Function binding happens during execution

V-Table

Virtual Table used internally by the compiler


Syntax of Virtual Function (Virtual Class)

class Base {

public:

    virtual void show() {

        cout << "This is Base class show function";

    }

};

Any class containing a virtual function becomes a virtual class


Virtual Class Works

  1. Base class pointer points to a derived class object
  2. The compiler checks the virtual function table (v-table)
  3. The correct function is called based on object type, not pointer type

This happens only when the function is declared virtual


Example: Using Virtual Function (Virtual Class)

Program

#include <iostream>

using namespace std;

 

class Base {

public:

    virtual void show() {

        cout << "Base class show function";

    }

};

 

class Derived : public Base {

public:

    void show() {

        cout << "Derived class show function";

    }

};

 

int main() {

    Base *b;

    Derived d;

    b = &d;

    b->show();

    return 0;

}

Output

Derived class shows function

 

Advantages of Virtual Class

Runtime polymorphism
Code flexibility
Better software design
Supports interface concept
Easy extensibility

 

Disadvantages

Slight performance overhead
Uses extra memory (v-table)
More complex debugging

=============================================================================

Post a Comment

0 Comments