33
Total Posts
3
Categories
24/7
Updated

C++

Write a C++ program to use pointer for both base and derived classes and call the member function. Use Virtual keyword.

Published on Dec 22, 2025
#include <iostream>
using namespace std;

class Base {
public:
    virtual void show() {
        cout << "This is Base class show() function" << endl;
    }
};

class Derived : public Base {
public:
    void show() {
        cout << "This is Derived class show() function" << endl;
    }
};

int main() {
    Base *bptr;        // Base class pointer
    Derived dobj;      // Derived class object

    bptr = &dobj;      // Base pointer pointing to derived object

    // Calling virtual function
    bptr->show();

    return 0;
}

Documentation

Output

This is Derived class show() function

----------------------------------------------------------------------------------------------------------

✔ Pointer to base class
✔ Pointer to derived class
✔ Virtual function usage
✔ Runtime polymorphism

 

Key Concept

  • A base class pointer can point to a derived class object

  • If the function is declared virtual, the derived class function is called at runtime

Explanation

  • virtual keyword ensures dynamic binding

  • Function call is resolved at runtime

  • Even though pointer is of Base type, Derived function is executed

  • This concept is called Runtime Polymorphism

  • Virtual functions are accessed using base class pointers