By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,918 Members | 2,246 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,918 IT Pros & Developers. It's quick & easy.

I finally figured it out! namespaces and the ODR

P: n/a
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::operator<<(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: <_c********************@speakeasy.net>
--
STH
Hatton's Law: "There is only One inviolable Law"
KDevelop: http://www.kdevelop.org SuSE: http://www.suse.com
Mozilla: http://www.mozilla.org
Jul 22 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"Steven T. Hatton" <su******@setidava.kushan.aa> wrote in message news:<vp********************@speakeasy.net>...

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


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

namespace sth {

std::ostream& operator<<(std::ostream& 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
Jul 22 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.