Problem
What is name hiding in C++?
Solution
Lets talk about 3 points :- Overriding
- Overloading
- Hiding
In Thinking in C++, 2e, Volume 1 (pages 632:646), Bruce Eckel had something similar to say, but he did specifically say overriding:
The redefinition of a virtual function in a derived class is usually called overridingOverloading
Overloading allows you to provide more than one definition for a function within the same scope.Hiding
Page 130 from C++ Programming in Easy Steps also mentions:
The technique of overriding base class methods must be used with caution however, to avoid unintentionally hiding overloaded methods – a single overriding method in a derived class will hide all overloaded methods of that name in the base class.
Let us explain through an example. In C++, when you have a class with an overloaded method, and you then extend and override that method, you must override all of the overloaded methods.
For example:
class FirstClass {
public:
virtual void MethodA (int);
virtual void MethodA (int, int);
};
void FirstClass::MethodA (int i) {
std::cout << "ONE!!\n";
}
void FirstClass::MethodA (int i, int j) {
std::cout << "TWO!!\n";
}
This is a simple class with two methods (or one overloaded method). If you want to override the one-parameter version, you can do the following:
class SecondClass : public FirstClass {
public:
void MethodA (int);
};
void SecondClass::MethodA (int i) {
std::cout << "THREE!!\n";
}
int main () {
SecondClass a;
a.MethodA (1);
a.MethodA (1, 1);
}
However, the second call won't work, since the two-parameter MethodA is not visible:
error: no matching function for call to ‘SecondClass::MethodA(int, int)’ note: candidates are: virtual void SecondClass::MethodA(int)
That is name hiding.Of-course, this is a basic post, but you would like to go deep, read more:
- http://stackoverflow.com/questions/10173211/confusion-regarding-name-hiding-and-virtual-functions
- http://stackoverflow.com/questions/4837399/c-rationale-behind-hiding-rule
- http://stackoverflow.com/questions/5928535/name-hiding-and-fragile-base-problem - a situation where changes to the base class can break code that uses derived classes (that being the definition I found on Wikipedia)
References
http://tianrunhe.wordpress.com/2012/04/13/name-hiding-in-c/
http://www.whyaskwhy.org/blog/907/c-overloading-overriding-and-hiding-oh-my/







0 comments:
Post a Comment