Skip to content

Instantly share code, notes, and snippets.

@CTimmerman
Last active August 29, 2015 14:20
Show Gist options
  • Save CTimmerman/db36f7d6a602b8eb3ed2 to your computer and use it in GitHub Desktop.
Save CTimmerman/db36f7d6a602b8eb3ed2 to your computer and use it in GitHub Desktop.
namespace_demo.cpp

Namespaces keep code contained to prevent confusion and pollution of function signatures.

Here's a complete and documented demo of proper namespace usage:

#include <iostream>
#include <cmath>  // Uses ::log, which would be the log() here if it were not in a namespace, see http://stackoverflow.com/questions/11892976/why-is-my-log-in-the-std-namespace

// Silently overrides std::log
//double log(double d) { return 420; }

namespace uniquename {
	using namespace std;  // So we don't have to waste space on std:: when not needed.
	
	double log(double d) {
		return 42;
	}
	
	int main() {
		cout << "Our log: " << log(4.2) << endl;
		cout << "Standard log: " << std::log(4.2);
		return 0;
	}
}

// Global wrapper for our contained code.
int main() {
	return uniquename::main();
}

Output:

Our log: 42
Standard log: 1.43508
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment