Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I put classes in separate files in C++? [closed]

Tags:

c++

file

class

I am asking this question to organize my code.

like image 695
Datoxalas Avatar asked Apr 05 '11 11:04

Datoxalas


2 Answers

C and C++ convention is one header file per library, or section of a library, rather than one header file per class. Try to group related classes together. So for example in the standard libraries <set> contains both std::set and std::multi_set, but then those are templates that do very similar things.

There isn't any truly consistent rule for public headers, though - Boost.asio has a big header file with a lot in it. Boost.DateTime is divided reasonably far down, although still not to the level of a single type.

You can put the implementations of the member functions in one source file per class if you like. Even one source file per function if you're following the GNU C style, although I don't think I recommend that for C++. And you could always implement your public-facing header files by having them include multiple separate headers.

It might depend as much on your version control and build processes as anything else - it's convenient to change a class without touching any files containing anything unrelated to the class, since then the bare minimum rebuilds and the changelog clearly identifies what has changed from the filename. But a class isn't necessarily the boundary of what's considered "unrelated code".

For example if you're writing collections with iterators, or classes that register listeners with some framework where the listener will act back on the main class, it doesn't make much sense to separate them. Morally speaking those are "inner classes" even if you don't implement them as nested classes in C++.

like image 77
Steve Jessop Avatar answered Oct 11 '22 13:10

Steve Jessop


I like to keep related classes in the same file.

For example, if I had a functor that was used in a for_each loop within a different class then I wouldn't generally put it in its own file. This seems excessive - and separates the code from where it is to be used too much.

However, in general I try to separate the classes out, and try have a sensible tree structure for the .hpp files that group together their use. At the head of this tree I like to have a catch all header file that includes the whole library.

like image 33
Tom Avatar answered Oct 11 '22 14:10

Tom