Virtual Function in C++ || C++
In this, we are going to see a program about Virtual Function in C++ Programming Language.



The Code given below can be used in TURBO C++ Compilers: -

#include <iostream.h>
#include <conio.h>

struct Base
{
    virtual void f()
    {
        cout << "base\n";
    }
};

struct Derived : Base
{
    void f()
    {
        cout << "derived\n";
    }
};

void main()
{
    Base b;
    Derived d;

    Base &br = b;
    Base &dr = d;
    br.f();
    dr.f();

    Base *bp = &b;
    Base *dp = &d;
    bp->f();
    dp->f();

    br.Base::f();
    dr.Base::f();
    getch();
    clrscr();
}

The Code given below can be used in gcc/g++ Compilers: -

#include <iostream>
using namespace std;

struct Base
{
    virtual void f()
    {
        std::cout << "base\n";
    }
};
struct Derived : Base
{
    void f() override
    { // 'override' is optional
        std::cout << "derived\n";
    }
};
int main()
{
    Base b;
    Derived d;

    // virtual function call through reference
    Base &br = b; // the type of br is Base&
    Base &dr = d; // the type of dr is Base& as well
    br.f();       // prints "base"
    dr.f();       // prints "derived"

    // virtual function call through pointer
    Base *bp = &b; // the type of bp is Base*
    Base *dp = &d; // the type of dp is Base* as well
    bp->f();       // prints "base"
    dp->f();       // prints "derived"

    // non-virtual function call
    br.Base::f(); // prints "base"
    dr.Base::f(); // prints "base"
}

#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post