Hi,
(大家好!我是一名来自中国的学生。)
I am a freshman from China.
Last week I bought this book.
It is a perfectly advanced C++ textbook.
But I meet some questions when reading.
for example, on page 255.
The author said that "There is a case where you actually can change the argument list for an overridden method. The trick is that the new argument list must be compatible with the old one."
I tried but failed. The code is as below, and compiler is Microsoft Visual Studio 2008
////////////////////////////
Code:
class Super
{
public:
Super(){}
virtual void someMethod() {
cout<<"in Super class"<<endl;
}
};
class Sub : public Super
{
public:
Sub(){}
virtual void someMethod( int i = 2 ) {
cout<<"in Sub class "<<i<<endl;
}
};
int main()
{
Sub mySub;
Super& ref = mySub;
ref.someMethod();
// calls the function in Super class!!!
// Polymorphism does not work!
return 0;
}
I guess override and polymorphism must satisfy several conditions:
first, the function signature must be exactly same, or
the return type is covariant;
second, of course, virtual keyword is necessary;
so the actually function call bind occurs in runtime, not compile time.
but overload occurs in compile time, because the compiler just append parameters in function name, so the function fun(int i) maybe fun_i, and fun(char ch) may be fun_c;
In this example above, the Sub class just define another function, not override the correspond function in Super class.