Virtual functions

From Yefu's notes
Jump to: navigation, search

Code

#include <iostream>

using namespace std;

class Base
{
public:
    virtual void Func()
    {
       cout<<"Base"<<endl;
    }
};

class Derived : public Base
{
public:
    void Func()
    {
        cout<<"Derived non virtual 1"<<endl;
    }
};

class Derived2 : public Derived
{
public:
    void Func()
    {
        cout<<"Derived 2 non virtual"<<endl;
    }
};

int main()
{
   Derived *d = new  Derived2;
   d->Func();
   
   Derived *d2 = new  Derived2;
   d2->Func();
   delete d;
   return 0;
}

output

Compiling the source code....
$g++ main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1

Executing the program....
$demo 
Derived 2 non virtual
Derived 2 non virtual