Virtual Methods

By using the keyword virtual in a method declaration we are able to implement Polymorphism (for derived objects of their base class type).

 

In the above section on upcasting we saw how the base class method was invoked for derived objects of a base class type. This problem is overcome by utilising virtual methods.

 

Simply by placing the keyword virtual against the base class method, we now get the desired behaviour :

#include <iostream>
#include <string>
using namespace std;

class BaseClass {
	public:
		virtual void speak(){
			cout << "BaseClass speak function." << endl ;
		}
};

class DerivedClass : public BaseClass {
	public:
		void speak(){
			cout << "DerivedClass speak function." << endl ;
		}
};

int main() {

    DerivedClass myObject ;  //declare DerivedClass object
    BaseClass *myPtr = &myObject;  //create BaseClass type pointer and assign to address of DerivedClass object
    myPtr->speak();  //use the pointer to invoke the method

    BaseClass *otherPtr = new DerivedClass;  //create BaseClass type pointer and assign to new DerivedClass
    otherPtr->speak();  //use the pointer to invoke the method

    return 0;
}

Compile & Run:

DerivedClass speak function.
DerivedClass speak function.

 

 

Only the base method declaration needs the keyword virtual (not the definition) and is then considered virtual in all derived classes, which (usually) override the method to provide the desired derived behaviour.

 

 

 

We are also still able to instantiate base class objects and call its method:

#include <iostream>
#include <string>
using namespace std;

class BaseClass {
	public:
		virtual void speak(){
			cout << "BaseClass speak function." << endl ;
		}
};

class DerivedClass : public BaseClass {
	public:
		void speak(){
			cout << "DerivedClass speak function." << endl ;
		}
};

int main() {

    DerivedClass myObject ;  //declare DerivedClass object
    BaseClass *myPtr = &myObject;  //create BaseClass type pointer and assign to address of DerivedClass object
    myPtr->speak();  //use the pointer to invoke the method

    BaseClass *otherPtr = new DerivedClass;  //create BaseClass type pointer and assign to new DerivedClass
    otherPtr->speak();  //use the pointer to invoke the method

    cout << endl ;
    BaseClass test;
    test.speak();

    return 0;
}

Compile & Run:

DerivedClass speak function.
DerivedClass speak function.

BaseClass speak function.

Leave a Reply