2

So, I am looking to make my code cleaner. Here is what I have:

obj.hpp

class obj {
    obj();

    int return0();
};

obj.cpp

using namespace obj; //illegal!!
obj() { }

int return0()
{
    return 0;
}

Basically, I think that writing obj::return0()... is a bit redundant. This becomes trickier when I have sub-classes, where I do things like obj::child::child2::return0()...

Any ideas?

Amil
  • 503
  • 1
  • 5
  • 13
  • http://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c This? – trumank Jun 13 '12 at 20:04
  • There's no way to do this in C++. – Etienne de Martel Jun 13 '12 at 20:05
  • You shouldn't normally have a nested class in a nested class in a class. You could use a typedef, though. – chris Jun 13 '12 at 20:05
  • 2
    If I'm reading you correctly you can just write the method implemtation in the header file. It's perfectly fine fo do so, if it was something like a template you would in fact HAVE to. – Patrick Borkowicz Jun 13 '12 at 20:06
  • 1
    possible duplicate of [Is it possible to avoid repeating the class name in the implementation file?](http://stackoverflow.com/questions/10887211/is-it-possible-to-avoid-repeating-the-class-name-in-the-implementation-file) – Rob Kennedy Jun 13 '12 at 20:23
  • @Patrick This is not necessarily fine. You can get in horrible ODR cases with this approach. – pmr Jun 13 '12 at 20:53
  • @RobKennedy Cool that is a duplicate of my question. I just wasn't able to find it through web searches >. – Amil Jun 13 '12 at 23:33

1 Answers1

3

using namespace x lets you call functions in x, not define them.

As a comment pointed out, you can inline the function in the header file if it's short.

obj.hpp

class obj {
    obj(){}
    int return0(){return 0;}
}
gcochard
  • 11,408
  • 1
  • 26
  • 41