2

I am making a static library, everything defined in it is all in one namespace. But I am unsure whether I should define the methods as if you would a class, or also wrap them in the namespace. What I'm asking is:

Is this valid:

MyThings.h

namespace MyThings {
    void DoStuff();
    void DoOtherStuff();
}

MyThings.cpp

namespace MyThings {
    void DoStuff() {
        // Do this.
    }

    void DoOtherStuff() {
        // Do that.
    }
}

Or, should I define it like I would class methods?:

MyThings.cpp

void MyThings::DoStuff() {
    // Do this.
}

void MyThings::DoOtherStuff() {
    // Do that.
}

I would prefer not to use using namespace MyThings;, and I would prefer to use my first example if it is valid, I feel it makes the code more readable without having to use MyThings:: before every method identifier.

2

1 Answer 1

10

Both are valid, so you can pick your style according to taste.

There is an advertised advantage of defining the function using:

void MyThings::DoStuff() {
    // Do this.
}

which is that in order to do it, the function must have already been declared. Thus, errors like:

void MyThings::DoStuf() {
    // Do this.
}

or

void MyThings::DoStuff(int i) {
    // Do this.
}

are caught when you compile MyThings.cpp. If you define

namespace MyThings {
    void DoStuff(int i) {
        // Do this.
    }
}

then you generally won't get an error until someone in another source file tries to call the function, and the linker complains. Obviously if your testing is non-rubbish you'll catch the error one way or another, but sooner is often better and you might get a better error message out of the compiler than the linker.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for the "must have been declared". for some strange reason i've never thought of that.
+1. Great answer, answers the question and tells me the implications of using my desired way of defining the functions in the namespace. I had never thought of that either.
+1 Good point about the link time error. I hadn't even considered that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.