Mr. Boy
Mr. Boy

Reputation: 63728

C++: Visibility of parent namespace to child namespace

If you have ns2 as a child namespace of ns1, and you use ns1 classes inside a header for an ns2 class, do you need to explicitly decalre it as you would when ns1 & ns2 are unrelated?

e.g

button.h

namespace ns1
{
 class Button
 {
  ...
 };
}

dialog.h

include "button.h"
namespace ns1
{
 namespace ns2
 {
  class TestDialog
  {
   Button *pButton;
  };
 }
}

Should that be right? It seems I have to change dialog.h to be:

namespace ns1
{
 ----->class Button;
 namespace ns2
 {

But I'm not quite sure why. Do namespaces not inherit? If I don't make this change, I get linker errors about "unresolved symbol ns1::ns2:Button::...".

Upvotes: 2

Views: 3371

Answers (3)

rubixibuc
rubixibuc

Reputation: 7397

You are missing a # sign, recompile with #include and you should be fine. The problem is when you don't include, you never actually declared the class in the other file.

Upvotes: 0

James
James

Reputation: 3231

Your code works fine for me in gcc 4.4.5 without the additional declaration of Button. You are missing a # from the include line, but I suppose that is just a transcription error. Are you sure that this is the part of your code that is causing the problem?

EDIT: In your actual code, you are probably not using the names ns1 and ns2 - maybe you have misspelled the namespaces somewhere?

Upvotes: 1

VDVLeon
VDVLeon

Reputation: 1394

All functions, classes (types), vars, etc. declared in a namespace will be available (without prefix) in all sub namepaces and so on. So when namespace n2 is defined in n1 all code in n2 can use n1 code without prefix.

Upvotes: 2

Related Questions