Namespaces, go figure...

May 1, 2011 at 6:37pm
So I am reading a c++ book, and this exercise shows up to question my knowledge about namespaces:

What is the output produced by the following program?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
using namespace std;

namespace Hello
{
  void message( );
}

namespace GoodBye
{
  void message( );
}

void message( );

int main( )
{
  using GoodBye::message;
  {
    using Hello::message;
    message( );
    GoodBye::message( );
  }
  message( );
  return 0;
}

void message( )
{
  cout << "Global message.\n";
}

namespace Hello
{
  void message( )
  {
  cout << "Hello.\n";
  }
}

namespace GoodBye
{
  void message( )
  {
    cout << "Good-Bye.\n";
  }
}


The answer I figured was: it will output error or crash or something like that, but instead the answer was:

Hello
Good-Bye
Good-Bye

So what did I understand wrong? Thanks in advance.
p.s. ask for more details if needed.
May 1, 2011 at 6:49pm
From what I can tell you missed the subtle difference between Line 18 and Line 22.
May 1, 2011 at 8:25pm
Namespace is the current scope of the segment of code being performed. Line 19 encloses lines 19-23 so any namespace changes inside of that segment will only affect that segment. Thus the call to use namespace Hello at line 20 and the output of message() at line 21 is "Hello". At line 22 the "Goodbye::message()" indicates that you are accessing the "Goodbye" namespace and calling the "message()" function within that namespace. Hence the output "Good-Bye". At line 24 the program is still using the "Good-Bye" namespace as declared at line 18 thus the last call to "message()" will again produce "Good-Bye".
Last edited on May 1, 2011 at 8:26pm
May 2, 2011 at 2:25pm
Ok thanks guys. What I was confused about was that I thought line 18 covers ALL the code from line 19 to line 26, therefore conflicting with line 21. But I guess I should have read the section twice. Thanks again, a lot!
May 2, 2011 at 2:39pm
line 18 covers ALL the code from line 19 to line 26
Yes, it does

therefore conflicting with line 21
No, it doesn't conflict since line 20 hides line 18 (this hiding mechanism is one vulnerability of C/C++)

You can write this:
1
2
3
4
5
bool ok = true;
{
bool ok = false; // no complain from the compiler
}
// ok is still true! 
May 2, 2011 at 7:06pm
ooooh, thanks a lot coder777, this namespace thing is confusing without practice, so any tips are welcomed.
Topic archived. No new replies allowed.