Search This Blog

Tuesday, July 13, 2010

Is it necessary to specify virtual keyword in derived classes? (C++)

No - not at all necessary! BUT please do it so that the maintenance programmer wont have horror experience debugging your code :)

Let me support it with sample code :


#include <iostream>

using namespace std;

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

class Derived : public Base {
public:
 Derived() { cout << "Derived::Derived()" << endl; }
 void VirtFun() { cout << "Derived::VirtFun()" << endl; }
 ~Derived() { cout << "Derived::~Derived()" << endl; }
};

int main () {
 
 Base* pBase = new Derived();
 pBase->VirtFun();
 delete pBase;

 return 0;
}

Output of this program is :
Base::Base()
Derived::Derived()
Derived::VirtFun()          
Derived::~Derived()
Base::~Base()

Even though the virtual keyword is not specified in the Derived class - the VirtFunc() and Destructor of virtual class are automatically virtual (because virtual keyword is specified for them in Base class).

Also note that : only the functions which are specified as virtual in Base class will be by default virtual in the Derived classes. If the function is not virtual in Base class - then it is not so.

I am not sure whether this features is compiler dependent or not, I have tested this code using 'Microsoft Visual C++ 2005' and G++, both give same output.

No comments:

Post a Comment