Namespaces and Overloading

C++You can overload functions across namespaces. For example:

// Original X.h:
  f(int);
 
// Original Y.h:
  f(char);
 
// Original program.c:
  #include "X.h"
  #include "Y.h"
 
void z()
{
  f('a'); // calls f(char) from Y.h
}

Namespaces can be introduced to the previous example without drastically changing the source code.

// New X.h:
namespace X {
  f(int);
  }
 
// New Y.h:
namespace Y {
  f(char);
  }
 
// New program.c:
  #include "X.h"
  #include "Y.h"
 
  using namespace X;
  using namespace Y;
 
void z()
{
  f('a'); // calls f() from Y.h
}

In program.c, function void z() calls function f(), which is a member of namespace Y. If you place the using directives in the header files, the source code for program.c remains unchanged.

Related References

IBM Copyright 2003