Sep 18, 2009

virtual methods and polymorphism

Today I had an interview. One of questions was about polymorphism in C++. The questions was whether we need to have "virtual" keyword in order to use polymorphism in C++. The correct answer is that C++ doesn't allow any methods to be used as polymorphism if it is not virtual method.

The confusion came from Java syntax, because every methods in Java are virtual methods. Although it is an understandable mistake for Java programmers, it should be always clear for C++ programmers.

Let's see an example here:
#include windows.h

class BaseClass
{
public:
void printSome() { OutputDebugStr( L"Base\n" ); }
};

class DerivedClass : public BaseClass
{
public:
void printSome() { OutputDebugStr( L"Derived\n" ); }
};

int _tmain(int argc, _TCHAR* argv[])
{
BaseClass * const obj = new DerivedClass();
obj->printSome();
delete obj;

return 0;
}
Which message should we expect to see? A correct answer is "Base" not "Derived", because it doesn't have "virtual" keyword.

The guy who raised this question to me was evaluating my technical skills on my interview. I doubt whether he graded me fairly. I wish he can find this article and correct his misunderstanding.

2 comments:

Anonymous said...

you know there is static polymorphism (e.g. operator overloading) and dynamic polymorphism(virtual, @ runtime).

So there is not always a need for the keyword "virtual" to use polymorphism.

Jay said...

You have a nice point. I haven't thought that operator overriding can be considered as polymorphism.

In deed, we use the way on template programming or template meta programming.

I might restrict the meaning of polymorphism too much. The emphasis of this article was more on run-time polymorphism.