Step 5 of 7
Namespaces and using
Large programs combine code from many libraries, and two libraries might both define a function called load or a type called Config. C++ avoids these clashes with namespaces: named scopes that group related names.
#include <iostream>
#include <string>
namespace audio {
int volume = 7;
std::string name() { return "audio"; }
}
namespace video {
int volume = 3;
std::string name() { return "video"; }
}
using std::cout;
int main() {
cout << audio::name() << " " << audio::volume << "\n";
cout << video::name() << " " << video::volume << "\n";
}
audio 7
video 3
namespace audio { ... }puts everything inside into theaudionamespace.::is the scope resolution operator:audio::volumemeans "thevolumeinsideaudio". Both namespaces have avolumeand there's no conflict.- The standard library lives in
std, which is why you writestd::coutandstd::string.
Shortening names
using std::cout;(a using-declaration) brings one name into scope, so you can writecout.using namespace std;brings in every name fromstd. You'll see it in tutorials, and it's fine in tiny programs, but it's a bad habit in real code:stdcontains hundreds of names, and pulling them all in invites clashes (with your owncount,max,distance, ...). Never put it in a header, where it would affect every file that includes it.
Most professional code simply writes std:: everywhere; it quickly becomes invisible.
Your turn: fill in the scope operators and the using-declaration.
Previous: bool, auto and range-for Next: Whole lines with getline