Markus
Markus

Reputation: 2222

Is it ok to split classes in multiple header files?

I've got a class that consists of a few functions and a lot of operators. Almost all functions and operators use templates which is why I've implemented them in the header file. This made it pretty hard to find something in the code so I decided to move all operators into a seperate headerfile.

now I have something like:

fstring.h

class fstring{
    ...
    #include "fstring_operators.h"
}

and fstring_operators.h

...
template<int RSIZE>
bool operator==(const fstring<RSIZE>& rhs) const {
    return equals(rhs._chars, RSIZE);
}
...

Is it ok to do something like this? I've also omitted header guards for fstring_operators.h because it must not be included anywhere except in fstring.h

Upvotes: 4

Views: 4560

Answers (2)

John Zwinck
John Zwinck

Reputation: 249103

I think you should define the methods as free functions. Then you can #include at the bottom of your regular header file, which is a practice that many C++ libraries use (some of them would make the operators filename end with .i or .inl or something).

If you do it that way it seems fine. The way you wrote in the OP is a little stranger, and even if it works, may throw off some maintainers of your code, and possibly even some development tools.

Upvotes: 5

Luchian Grigore
Luchian Grigore

Reputation: 258548

Although I've seen this in production code before, I don't really agree with this style for 2 reasons:

1) You expect a class to be fully defined in the header. You shouldn't need to look inside other headers to find what you're looking for.

2) You can include the other header elsewhere. Even without include guards, it's not a guarantee it won't work.

Upvotes: 7

Related Questions