TITLE: More thoughts on namespaces


PROBLEM: Mike Ladwig <mike@twinpeaks.prc.com>

The following code worked fine on gcc (g++) versions prior to 2.5.7:

g++ used to be broken in this respect.

class a {
public:
        virtual void f( void ) { cerr << "Afvoid"; };
        virtual void f( int ) { cerr << "Afint"; };
};

class b : public a {
public:
        virtual void f( int ) { cerr << "Bfint"; }
};

main() {
        b       foo;
        foo.f();  // error
}


RESPONSE: jamshid@ses.com (Jamshid Afshar), 11 Apr 94

The error is correct: a derived class' member names *hide* any
functions of the same name in base classes.  The fact that they're
virtual doesn't really have anything to do with it.  Normally I reply
to this frequently asked question with a note that it's discussed in
the comp.lang.c++ FAQ list (and you should still read it before
posting), but I recently came across the following in Stroustrup's new
_The Design and Evolution of C++_ 17.5.1:

	If this [hiding] isn't what we wanted, we can use a
	using-declaration to bring B's f() into scope:

	class B {
	public:
	   void f(char);
	};
	class D : public B {
	public:
	   void f(int);
	   using B::f;  // bring B::f into D to enable overloading
	};
	[...]
	We suddenly have a choice!
	[...]
	An explicit mechanism along these lines has been suggested
	repeatedly over the years.  I remember discussing the
	possibility with Jonathan Shopiro while working on release
	2.0, but rejecting it as being "too specialized and unique"
	to include.  The using-declaration, on the other hand, is a
	general mechanism that just happens to provide a solution to
	this problem.

The `using' keyword is part of the new namespace feature recently
accepted by the ANSI/ISO C++ committee to handle the mixing of
different libraries that use the same global class or function names.
Namespaces are briefly described in the ANSI/ISO Resolutions ARM/CPL2
appendix (a ps file is at world.std.com:AW/stroustrup2e).  It's more
completely described in D&E, a book I highly recommend to anyone
wanting to know more about new C++ features like RTTI and namespaces,
or wanting to know what's going on with template extensions, etc.
Encourage your compiler writer to implement this feature soon
(Stroustrup wrote that it isn't difficult).


