Question

Well, this is a pretty trivial question. But i'd like to know if it is okay to put multiple classes into one header / source file. I've often enough seen that for every class there is another header and another source file, like it is in Java (not only by Convention...)

I see the ups and downs here: on the one hand you might want to have some relevant classes on one place for editing, since big projects sometimes require you to search a bit for them. On the other hand, more files make single files less heavy, so you don't have to scroll down tousands of lines to get to the method you're searching.

Now what do the Conventions say about that?

[Example]

At the moment i have 3 classes in one file: a Server, A ClientHandler for the Server and a ServerManager. The server manages the connections, the ClientHandler manages all in- and outgoing traffic for each client and the ServerManager contains some logic i need to run the Server.

[Edit] be gentle with my abilities of the english language, i'm foreign ;)

Was it helpful?

Solution

It's considered good form for each class to have its own header/implementation pair.

The most compelling reason (for me) is that the files are named after the class they contain. This makes it easy to find the correct file for a declaration in the code. If a file has more than one type in it, it becomes harder to name, and therefore harder to maintain.

However, sometimes it's not so clear cut. A "main" class might have some other supporting class that's definitely part of its interface (in the Herb Sutter sense of interface), but doesn't rightly belong as a nested type. This should be rare, but such a case might justify having more than one class per file.

If you've gone to the trouble of abstracting out concepts (such as in the example you give), why not go the extra little bit and put them in their own files? You will thank yourself for it down the line!

OTHER TIPS

There's no real rule, other than common sense. If two classes are closely linked, it's common to put them in the same header. And of course, not everything in C++ is a class; free functions may be grouped in various different headers according to whatever seems most logical.

Also, there isn't always a one-to-one relationship between headers and source files. If your class is a template, there may not be a source file at all. On the other hand, if you're writing a library that will be widely used, and the class isn't polymorphic, you'll probably want to put each function in a separate source file.

And a lot of classes are defined directly in source files, and not in headers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top