4

When declaring and implementing a class or struct in c++ we generally do:

H file

namespace Space{
  class Something{
    void method();
  }
}

CPP file

void Space::Something::method(){
  //do stuff
}

OR

namespace Space{
  void Something::method(){
    //do stuff
  }
}

Note how it is possible to wrap all the implementations inside the namespace block so we don't need to write Space:: before each member. Is there a way to wrap class members in some similar way?

Please note I want to keep source and header file separated. That's generally a good practice.

ButterDog
  • 5,115
  • 6
  • 43
  • 61

4 Answers4

3

Not without sacrificing the separation between header and implementation (cpp) file.

You can declare everything inline in the header inside the class, but it's very messy for large classes.

What's the problem you're actually trying to solve? Or is it just typing time? :)

SteveLove
  • 3,137
  • 15
  • 17
  • Is not that it causes any problem, I declare the methods on the H file and then I generally copy those lines to the source file but I've just found myself adding the *Classname::* so many times that it has become bothersome. I just wonder if there is a way to wrap namespaces, there might be a way to wrap classes. – ButterDog Jul 31 '13 at 16:18
2

Yes:

.h file:

namespace Space{
  class Something{
    void method()
    {
      // do stuff
    }
  };
}

I don't recommend it, though.

greatwolf
  • 20,287
  • 13
  • 71
  • 105
Bill
  • 14,257
  • 4
  • 43
  • 55
  • This will do it. But, as Bill implies, this is potential for bad practice. You will want to keep header and implementation files separate. – Paul Renton Jul 31 '13 at 16:06
  • Thats convenient to write but there's still a good reason to keep the implementation on their own CPP files. – ButterDog Jul 31 '13 at 16:07
  • @Xocoatzin: Exactly why I don't recommend it. I like separating declarations and definitions. – Bill Jul 31 '13 at 16:08
1

No, unless you put the class members directly into the class definition

class Something
{
    void method() {}
};

This is discouraged as it leads to header bloat if your class definition is in a header file.

I prefer not to use the wrapping method myself, so each function body explicitly states its namespace. This helps detect typos or dead code if you remove the prototype.

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
1

You can not if you keep the .cpp file.

Otherwise, you can, but you would essentially just be dropping the .cpp file.

In your .h file, you could have:

namespace Space{
  class Something{
    void method()
    {
      //Method Logic
    }
  };
}

Except, as you know, there would be limitations as to where you could include the header.

I'm not so sure this will help you, the OP, as you seem to know what you're doing, but I'll include it for future users of the question:

What should go into an .h file?

Community
  • 1
  • 1
James Hurley
  • 833
  • 1
  • 10
  • 33