I finally figured it out! namespaces and the ODR

S

Steven T. Hatton

A while back I posted some code along with an error message I got when I
tried to compile it. I thought at one point I had solved all the problems.
But then I tried it again, and if failed. The code I posted here didn't
have namespaces in it. I had originally tried to compile the same code
with namespaces. The one subtlety I missed was that overloaded operator
definitions are namespace local. If I declare this in my header file:

//BaseNode.hh
namespace sth{
ostream& operator<<(ostream& out, const BaseNode& bn);
}

I have to qualify the operator<<(...); like this:
//BaseNode.cc

ostream& sth::eek:perator<<(ostream& out, const BaseNode& bn)
{
return bn.print(out);
}

Note the sth:: before the operator<<(..) I had not been doing that. That
caused the compile to fail. I then put the definition back in the header
file, and that violated the ODR. Put all the code in one file, and it all
worked fine.

This is the original message I'm referring to:
news://Message-ID: <[email protected]>
 
D

David Rubin

[snip]
//BaseNode.hh
namespace sth{
ostream& operator<<(ostream& out, const BaseNode& bn);
}
I have to qualify the operator<<(...); like this:
//BaseNode.cc
ostream& sth::eek:perator<<(ostream& out, const BaseNode& bn)
{
return bn.print(out);
}

Alternately, you can define operator<< in BaseNode.cc like this:

namespace sth {

std::eek:stream& operator<<(std::eek:stream& stream,
const BaseNode& node)
{
// implementation
}

} // close namespace sth

It is considered bad practice by many to state 'using namespace std;'.
Therefore, you should always use fully qualified names. Note that it
is *not* a good idea to write BaseNode.cc like this (for example):

using namespace sth;

void freeFunction(void) { /*...*/ }

Since 'freeFunction' might clash with a symbol from another namespace
dragged into BaseNode.cc from another header file.

HTH, /david
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top