Name hiding in C + +, name lookup takes precedence over type checking

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.