Topic
What is name hiding in C + +?
Answer
Let's use an example to illustrate the hiding of names in C + +. In C + +, if there is an overloaded method in a class, you use another class to inherit it and rewrite (overwrite) that method. You must override all overloaded methods, otherwise the overridden method will be hidden because the name is the same, making it invisible in the derived class.
Take a look at the example:
classfirstclass{ Public: Virtual voidMethodA (int); Virtual voidMethodA (int,int);};voidFirstclass::methoda (inti) {cout<<" One"<<Endl;}voidFirstclass::methoda (intIintj) {cout<<" Both"<<Endl;}
There are two methods (overloaded methods) in the class above, and if you want to override a function in a derived class, you can do this:
classSecondclass: Publicfirstclass{ Public: voidMethodA (int);};voidSecondclass::methoda (inti) {cout<<"three"<<Endl;}intMain () {Secondclass A; A.methoda (1); A.methoda (1,1); return 0;}
In the main function above, the 2nd MethodA will error at compile time, suggesting that there is no function to match. This is because the MethodA of the two parameters is not visible in the derived class, which is the name hiding.
name hiding is independent of virtual function . so regardless of whether the two functions in the base class are virtual functions, name hiding occurs here . There are two solutions. The first one is to change the MethodA of the 2 parameters to a name, which is visible in the derived class. But since we overloaded the MethodA, it means that they are only different in parameters and should actually be doing the same or similar things. So it's not a good idea to change names. Therefore, we typically use the second method to override all overloaded functions in a derived class.
Name hiding in C + +, name lookup takes precedence over type checking