Example of Virtual Function

 Here are two examples demonstrating Virtual Functions in C++:


1️⃣ Basic Example of Virtual Function

📌 Explanation: A virtual function allows function overriding in a base class so that the derived class’s function gets called.

#include <iostream>
using namespace std;

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

class Derived : public Base {
public:
    void show() override {  // Overriding the base class function
        cout << "Derived class show() function" << endl;
    }
};

int main() {
    Base* ptr;  // Base class pointer
    Derived obj;
    ptr = &obj;

    ptr->show();  // Calls Derived class function due to virtual function

    return 0;
}

📝 Output:

Derived class show() function

2️⃣ Load Features Example in C++

📌 Explanation: This example simulates loading different types of features based on user selection.

#include <iostream>
using namespace std;

class Feature {
public:
    virtual void load() {  // Virtual function
        cout << "Loading basic features..." << endl;
    }
};

class PremiumFeature : public Feature {
public:
    void load() override {  // Overriding the virtual function
        cout << "Loading premium features..." << endl;
    }
};

class VIPFeature : public Feature {
public:
    void load() override {  // Another override
        cout << "Loading VIP exclusive features..." << endl;
    }
};

int main() {
    Feature* f;
    PremiumFeature p;
    VIPFeature v;

    f = &p;
    f->load();  // Calls PremiumFeature’s load()

    f = &v;
    f->load();  // Calls VIPFeature’s load()

    return 0;
}

📝 Output:

Loading premium features...
Loading VIP exclusive features...

Thank you for joining us!💖

Post a Comment

0 Comments