I personally don't like this, but sometimes it's useful. The Standard library uses this too:
stringstream ss;
/* Imagine you want to redirect all output that goes into "ss"
* to "cout". The following does NOT work! */
ss.rdbuf(cout.rdbuf());
Why does it not work? Because stringstream
has hidden ios::rdbuf
with a same named function that only provides read access to its internal std::stringbuf
, rather than to the attached buffer. You need to do the following
ss.std::ios::rdbuf(cout.rdbuf());
Now, the buffer attached to the stream is not equal to what ss.rdbuf()
returns. I personally dislike this design though.
I once had a good use of hiding though. In my opinion, hiding needs one requirement:
- The behavior should be the same.
In my case, I had a base class like this (not really near as it was, but it's conveying the situation).
template<typename T>
struct A {
void doSomething() {
T t;
t.doIt();
}
};
class Foo;
struct B : A<Foo> {
};
B b;
What happens when one calls b.doSomething()
? It needs the header of Foo
, because the function wants to call doIt
on the class and creates a variable of that type. The workaround was simple
class Foo;
struct B : A<Foo> {
void doSomething();
};
// and in the .cpp file:
#include "Foo.h"
void B::doSomething() {
A<Foo>::doSomething();
}
This way, I prevented that every user of my B
class needs to include the Foo's header. Only B's cpp file, which knows it depends on "Foo", has to do this.