I am so confused with the term name hiding and information hiding. Most importantly, What is the hiding rule in c++? Can someone give me a definition?
-
Where did you hear the terms? – GManNickG Sep 08 '13 at 21:28
-
There is nothing formally named "The Hiding Rule". There are more than a few rules dealing with hiding, generally of multiple items sharing the same identifier (textual name). Can you be more specific as to what you're talking about. – Ben Voigt Sep 08 '13 at 21:41
3 Answers
Name hiding happens when you override a class:
struct A
{
int x;
int y;
void foo();
void bar();
};
struct B : A
{
int y;
void bar();
};
In class B
, the names x
and foo
are unambiguous and refer to the names in the base class. However, the names y
and bar
hide the base names. Consider the following:
B b;
b.bar();
The function name refers to the name of the function B::bar
without ambiguity, since the base name is hidden. You have to say it explicitly if you want the base function: b.A::bar()
. Alternatively, you can add using A::bar;
to your class definition to unhide the name, but then you have to deal with the ambiguity (this makes sense if there are distinct overloads, though).
Perhaps one of the most frequently confusing examples of name hiding is that of the operator=
, which exists in every class and hides any base class operator; consequently, an implicit definition of the operator is produced for each class which doesn't provide an explicit one, which may come as a surprise if you already defined an assignment operator in a base class.

- 464,522
- 92
- 875
- 1,084
-
2More generally, name hiding happens whenever the same name exists in an inner scope and an outer scope. `int a = 1; { int a = 2; } assert(a == 1);` Derived class and base class are one example of an inner scope and an outer scope. – Oktalist Sep 08 '13 at 21:32
-
@Oktalist: Thanks, that's a very good point. One should note that there's a limit to how far you can access such arbitrarily hidden names, though; `::a` will only get you so far. – Kerrek SB Sep 08 '13 at 21:33
Information hiding is the same as encapsulation. Here is a good starting point http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29

- 59,252
- 17
- 87
- 127
The "hiding rule" says that if you derive a class and add a member with the same name of a member in the parent this member will "hide" the parent version:
struct Base {
void foo();
};
struct Derived : Base {
void foo(int);
};
here if you try to use foo()
in a derived instance method you will get an error, even if indeed there is a foo()
available in Base
.
The given reason for this is to avoid confusion where for example base could have void foo(double)
and derived void foo(int)
. The rationale is that it's better to have compiling to stop instead of having just an unexpected behaviour in the resulting program.
You can "import" base names in the derived class, but this must be done explicitly with using
.

- 112,025
- 15
- 165
- 265