M-Wi
M-Wi

Reputation: 452

Proper use of c++ namespace

I'm new to c++ and have a project with a handful of classes broken out into separate header and source files.

It would be very convenient for a few of these classes to have access to shared utility methods for validating keyboard input. This is because I don't want the class methods to be clogged up with long, identical code handing input stream/ buffer etc.

I found this answer recommending namespaces for this kind of problem, but I don't understand how to incorporate a namespace into my project.

For example, say I have

// Utility.h
namespace utility {
  method1() {...}
  method2() {...}
  etc..
}

is it improper to then do this:

// Foo.h
#include "Utility.h"
class Foo {
  void bar();
}

// Foo.cpp
#include "Foo.h"
void foo::bar {
  ..do stuff..
  utility::method1()
  ..do more stuff..
}

Where "Foo" may actually be a few classes identically using utility?

My intention: I'm interested to use utility methods only in the body of class methods to make the code more readable where identical checks are happening in multiple class methods.

Edit: added question I have referenced

Upvotes: 0

Views: 924

Answers (2)

Jean-Marc Volle
Jean-Marc Volle

Reputation: 3333

It is perfectly fine. You can even do:

void foo::bar {
  using namespace utility;
  method1():
  ..do more stuff..
}

In case a .cpp needs to include many headers (with their respective namespace), it helps your reader better understand which namespace are used in which of your functions.

The only stuff that you should not do is using namespace in your .h because by doing so you force anyone using your .h to also use the namespace you "used".

Upvotes: 0

Asteroids With Wings
Asteroids With Wings

Reputation: 17464

Yes, you can define functions in a namespace, and yes you can then use those functions in different parts of your program, and yes that is how you call them.

No, there is no style or compiler problem with using namespaces.

Upvotes: 2

Related Questions