Jacob Soffer
Jacob Soffer

Reputation: 304

How to use namespaces and classes?

Sorry if this is a dumb question, but I am learning C++ (I usually code in C) and I don't understand how to use namespaces and classes. Do they have to be declared in header files? How do I declare functions in a namespace? And let's say I am working on a large project with different files. And I define a namespace in a file, but then want to add more functions to that same namespace, but those functions are defined in another file. Can that be done? For example:

file1.cpp

namespace Example {
   int vartest;
   void foo();
}

file2.cpp

int othervar;
void otherfoo(); // How can I add this and othervar to the Example namespace?

Thanks!

Upvotes: 3

Views: 777

Answers (1)

WhiZTiM
WhiZTiM

Reputation: 21576

Simply declare it an equivalent1 namespace of the same "name" !

file1.cpp

namespace Example {
   int vartest;
   void foo();
}

file2.cpp

namespace Example {
    int othervar;
    void otherfoo();
}

Namespaces are merged.

Do they have to be declared in header files?

No. You can declare any namespace inside a namespace. (Note that the "global scope" is also a namespace)

How do I declare functions in a namespace?

Simply declare it within the namespace. As you have done.

And let's say I am working on a large project with different files. And I define a namespace in a file, but then want to add more functions to that same namespace, but those functions are defined in another file. Can that be done?

Namespaces of the same name, within the same namespace are merged.

namespace X { void foo(){} }
namespace X { void foo(){} }  //Error, redefinition of `foo` because the namespace ::X is merged

namespace X { void foo(){} }
namespace Y { void foo(){} }  //Ok. Different name spaces... 

namespace X { void foo(){} }  // ::X
namespace Y { void foo(){} }  // ::Y

namespace Y {
   namespace X {  // namespace ::Y::X here isn't same as ::X
     void foo(){}  //OK
   }
}

1 recall that the so called "global scope" is actually a namespace known as global namespace

Upvotes: 4

Related Questions