Virtual Function in C++

I think it would be the best if we run an example first, so let’s do that:

#include <iostream>
#include <string>

using namespace std;

class Base
{
public:
    string nonVirtualMethod() {
        return "Base: non virtual method.";
    }
    virtual string virtualMethod() {
        return "Base: virtual method.";
    }
};

class Derived : public Base
{
public:
    string nonVirtualMethod() {
        return "Derived: non virtual method.";
    }
    string virtualMethod() {
        return "Derived: virtual method.";
    }
};

int main()
{
    Derived *derivedObject = new Derived();
    cout << "Derived::non-virtual(): -> " << derivedObject->nonVirtualMethod() << endl;
    cout << "Derived::virtual(): -> " << derivedObject->virtualMethod() << endl;
    cout << endl;

    Base *baseObject = new Derived();
    cout << "Base::non-virtual() -> " << baseObject->nonVirtualMethod() << endl;
    cout << "Base::virtual() -> " << baseObject->virtualMethod() << endl;
    cout << endl;

    return 0;
}

As we can see from the example, when a method is declared “virtual”, the method of the defined class is used. Let’s further dive into this.

Base *baseObject = new Derived();

 

Non-Virtual Function
Without the virtual keyword added, methods look for their definition in the declared class. When calling baseObject->nonVirtualMethod(), the compiler looks at the type of the baseObject (which is Base) and then runs function definition in Base class.
So, non-virtual functions looks at: Base *baseObject => Base

Base *baseObject;
baseObject->nonVirtualMethod(); //Calling Base::nonVirtualMethod

 

Virtual Function
On the other hand, because baseObject is instantiated as Derived object (and we most often want to use the derived method instead), when we call baseObject->virtualMethod(), it checks out what the type baseObject is really pointing to (baseObject = new Derived()), then runs the function definition from Derive class.

Virtual function looks at: baseObject = new Derived() => Derive

baseObject = new Derived();
baseObject->virtualMethod(); //Calling Derived::virtualMethod

Hope this kinda help.

Advertisements