Table of Contents
*This post may contain affiliate links. As an Amazon Associate we earn from qualifying purchases.
During you C++ interview, the topic of name hiding might come up. Let us tell you everything you need to know about this so that you can impress your interviewers and get the job.
What Is Name Hiding in C++?
The process referred to as “name hiding” in the C++ language entails the explicit declaration of the name of a class in a derived class or a nested declarative region. The purpose of this process is to avoid unforeseen and counter-intuitive errors that might come up if the overloaded functions that are inherited would mix with the overloads in a class.
To get a better idea of what this means, you should know that in C++ if the name of a class or an enumeration is in scope and it is not specifically hidden, this name is visible.
In order to hide it, programmers are required to explicitly declare the same name as the class, object, or enumeration in the nested declarative or the derived function. Another thing you need to remember is that the name of the class or the enumeration is hidden when the function, object, or enumeration is visible.
In fact, in a member function definition, declaring a local name will hide the declaration of a member of this class that has the same name. Also, declaring a member in a derived class will hide the declaration of a member of the base class that has the same name.
How to Use Name Hiding in C++
We’re going to present a name hiding example so that you can get a better idea of what name hiding in C++ entails. In the following example, the name “t” is a member of namespace “X”. Also, the members of namespace “X” are visible in namespace “Y” by using a declaration. Declaring the object named “t” in namespace “Y” will hide “X”. Take a look!
The output of out example is “int” because the name “t” has been successfully hidden.
Although name hiding in C++ is meant to eliminate errors and faults in your code, it can sure become a stress factor if you don’t exactly know why it exists and how it works. We hope this article has provided all the details you will need to answer this IT interview question.