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.hclass 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.