#include <cstdlib> #include <iostream> using namespace std; class Base{ public: virtual void func(){ cout << "Base::func()" << endl; } virtual int func( int num ){ cout << "Base::func( int " << num << " )" << endl; return 0; } }; class Derived : public Base{ public: virtual void func(){ cout << "Derived::func()" << endl; } }; int main(){ Derived d; d.func(); d.func(1); system("PAUSE"); }The compile result is :
D:\Projects\C++\tmp\tmp\test.cpp: In ‘int main()
D:\Projects\C++\tmp\tmp\test.cpp:36:10: error:The call to ‘Derived::func(int)’ has no matched function
D:\Projects\C++\tmp\tmp\test.cpp:36:10: The alternative is
D:\Projects\C++\tmp\tmp\test.cpp:26:15: virtual void Derived::func()
D:\Projects\C++\tmp\tmp\test.cpp:26:15: The alternative function requires 0 parameter, 1 is provided
He doesn't know why this compilation error occurs. He used virtual in the base class, he should be able to call the base class's
int func( int num )method, but unfortunately, it is not working.
The reason for this compilation error is that in C++ standard 2003, there is a statement says:
3.3.7 Name hiding [basic.scope.hiding]
1 A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived
class (10.2).
So here in the derived class, the
void func()method overrides the method in the Base class and it also hides the base class's method with 1 parameter which is
int func( int num )here even if you use virtual in Base class, it's no use for the Derived class.
Then some people ask whether this is a C++ bug or not because they think if they don't override the base class's method, they should be able to use it in derived classes, this is more logical. But in C++ standards, it says this conforms to the standard. I don't know why the designers choose this design.
Do you have any idea why C++ designer design this feature?
Reference:http://topic.csdn.net/u/20120508/10/2935efc4-3289-4309-a903-46e16ed16449.html