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

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am asking this question to organize my code.

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++.

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.

Yes. As a general rule, one class per pair of .h/.cpp. Files should be named after the class.

It depends on the application. With some applications, it makes sense to group different classes together in one set of .h/.cpp files if they are tightly coupled. Otherwise the standard of splitting a class into header and source files is definitely the proper way to do it.

You should put C++ classes in separate files if it makes sense to do so. With well designed classes, it often does. It makes for easy coding, maintenance, modularity, refactoring and reuse.
Then you have MyClass.h which contains class MyClass {...} and MyClass.cpp which contains all of MyClass's methods.
If you have lots of small classes, this gets a bit crazy so consider a couple of options:
File named after a namespace, e.g. MyNamespace.h, MyNamespace.cpp
Nested classes - does it make sense to wrap a class definition inside another class? By doing this you are saying that the nested class is unlikely to be useful without its parent.
It is nice to avoid an extra set of naming conventions, by making each file name consistent with a C++ namespace or class names one avoids the need to think up new names or convert from one convention to another.
Google style guide has an opinion too, preferring filenames with underscore. See http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#File_Names

Yes it is a good practice to keep separate classes in separate cpp files and then name the files by using the class name. In fact Java forces you to do so.

Related

Is it good practice to declare derivate classes in the same C++ header? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
Improve this question
I'm declaring a pure virtual class that will provide a unified interface for a handful of derived classes. My instinctual way to organize this would be to create a base folder with the header for the base class (e.g lib/Base.h) and then create subfolders for the header + source file of the derived classes (so lib/implA/ImplA.h,lib/implA/ImplA.cpp and so forth). This keeps the files short, but feels cluttered.
Would it be considered good practice to gather the definitions of the derived classes in the header lib/Base.h and keep the various implementations in the same folder?
It is neither good nor bad. What matters is what you want to present as an API, that is what a user or your classes will have to write in their own sources. #include "lib/implA/ImplA.h" uses 2 directory level which is not very common while not being too much either IMHO. It can makes sense if a single application will seldom use more than one implementation.
For the way you want to organize your headers and translation units, it is really a question of having reasonable sizes. And the magnitude order may vary between teams...
Two-file folders (like lib/implA/ImplA.h, lib/implA/ImplA.cpp) are unnecessary, for small projects people usually just put everything in lib/. If lib/ becomes too cluttered, put this whole hierarchy in lib/my_hierarchy/Base.h, lib/my_hierarchy/ImplA.cpp, etc. Maybe extract a logical subsystem instead of a hierarchy. Just keep reasonable folder sizes and some organized structure.
As for putting multiple declarations in the same header, it's your design choice. As far as I know, there's no single "best practice" in C++ regarding this. C++ doesn't enforce one class per file, like Java does. However, including a lot of classes in a single header means slightly longer compilation times for users, because that long header needs to be parsed in every .cpp file where it's #included. Usually people try to keep their headers minimal, but also provide a convenience "aggregate" header that includes all other headers (like bits/stdc++.h for the standard library). In your case, that would be:
// lib/lib.h
#include "my_hierarchy/Base.h"
#include "my_hierarchy/ImplA.h"
// etc.
So that users who don't mind longer compilation times can just #include <lib/lib.h> and have everything, while others can #include only classes they need.

C++ Conventions: Structure of Headers and Classes [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this 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 ;)
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!
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.

Multiple files and Object Oriented Programming

In my application, I use multiple files, each file contains a class, is it a good idea to gather all C++ files (implementation of all classes) in one file and gather all headers in another file, or this is not good for some reason but code organizing ?
Keeping declarations and definitions organized in to separate but related translation units can help to decrease compilation times.
And don't disregard the value of keeping things organized for humans too! Software can consist of many thousand different objects, functions, and other parts. Keep it as simple as possible (but no simpler)!
If you keep declaration and definitions of a class in the corresponding files, they need only to be recompiled when you made changes in these class. Also changes in one class only requires relinking of the changed class against the classes which depend on it. Therefore it decreases compile time.
It makes it also much more easier to debug, as the compilation errors can be traced back to one file.
There is no advantage to concatenate all files in one, as far as I know
In C++ it really doesn't matter so much. In some languages, such as Java, the compiler requires that every class be in a separate file, but as long as you make sure that the different files reference each other there is no reason either way.
Perfectly agree with other answers, and I would like to add my piece :
Breaking into several files also make it easier when using an editor. You can then use several tabs. (Imagine if your browser displayed all your pages one after another in one window only !)
It is even acceptable to break a class implementation in several files if the implementation is big.
On the other hand, there are sometimes reasons to put several classes in one file, for example when those classes are small and/or very highly related. For example a FooObject and its FooAllocator, or a FooObject and its small FooSubObject used only by him.

Organizing large C++ project

Should all C++ code in a project be encapsulated into a single class with main simply calling that class? Or should the main function declare variables and classes.
If you are going to build a large project in C++, you should at the very least read Large Scale C++ Software Design by John Lakos about it. It's a little old but it sounds like you could benefit from the fundamentals in it.
Keep in mind that building a large scale system in any language is a challenge and requires skill and discipline to prevent it falling to pieces very quickly. Don't take it lightly.
That said, if your definition of "large" is different than mine then I may have alternative advice to give you. I'm assuming you're talking about a project where the word "million" will be mentioned in sentences that also contain the words "lines of code".
for large C++ projects, you should create many classes!
main should just kick things off (maybe doing a few housekeeping things) and then calling into a class that will fire up the rest of the system
If it's a class that really makes sense, sure -- but at least IME, that's a fairly rare exception, not the general rule.
Here, I'm presuming that you don't really mean all the code is in one class, but that there's a single top-level class, so essentially all main does is instantiate and use it. That class, in turn, will presumably instantiate and use other subordinate classes.
If you really mean "should all the code being contained in a single class?", then the answer is almost certainly a resounding "no", except for truly minuscule projects. Much of the design of classes in C++ (and most other OO languages) is completely pointless if all the code is in one class.
If you can put your entire project in one class without going insane, your definition of "large" may be different than most people's here. Which is fine -- just keep in mind when you ask people about a "large" c++ project, they will assume you're talking about something that takes multiple person-years to create.
That said, the same principles of encapsulation apply no matter what the size of the project. Break your logic and data into units that make sense and are not too tied together and then organize your class(es) around those divisions. Don't be afraid to try one organization and then refactor it into another organization if you find yourself copy-pasting code, or if you find one class depending too heavily on another. (Or if you find yourself with too many classes and you're creating many objects to accomplish one task where a single object would be cleaner and easier on you.)
Have fun and don't be afraid to experiment a little.
In C++ you should avoid putting entire project in one class, irrespective of big or small. At the max you can try putting it in 1 or 2 namespace (which can be split across the files).
The advantage of having multiple classes are,
Better maintainability of your code
Putting classes in multiple .h and .cpp files (i.e. small modules) help you fast debugging
If all code is in one class and changes are made somewhere then one has to compile whole project. Instead, if project is across modules, one can just compile the module where changes are made. It saves time a lot.
No! Each header/implementation file pair should represent a single class. Placing a large project in one file is a surefire way to disaster: the project become unmaintainable and compiling will take ages. Break up your code in to appropriately sized pieces.
The main function should not declare the classes, rather, the file it contains (often named something like main.cpp, driver.cpp, projectname.cpp) should use #include directives to make the compiler read the declarations in header files. Read up on C++'s separate compilation model for more info.
Some newcomers to C++ find the compilation model - as well as error codes generated when you screw it up - incomprehensible or intimidating and give up thinking it's not worth it. Don't let this be you. Learn how to properly organize your code.

What C++ refactorings do you use in practice? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm going to create the comparison table of existing automated C++ refactoring tools as well as explore an ability of creation of such tool, free and open-source.
My question is: what refactorings do you really use in your everyday work? There are obvious things like renaming variable/class/method, but is there something specific for C++, like dealing with templates, STL, copy constructors, initializers, etc., etc?
I'm interested in building of realistic picture of all that little problems that C++ developer is facing each day in his coding and that could be automated at least in theory. I'm talking to my colleagues but that's probably not enough.
Thanks in advance.
It is pretty clear from the answers that few C++ programmers have ever seen a real refactoring tool. Yes, they are quite rare and highly specific to the IDE you use. That's inevitable, there is otherwise no good way to find out what source code files contribute code to the final executable. The preprocessor makes it extra challenging, you need to know the macro values. A source code parser is required but not enough.
Visual Assist for VS is one I know of.
As you said there are obvious things:
renaming is one
altering a function signature is another (especially since a function is almost necessarily duplicated: declaration in the header and implementation in the source)
renaming / moving a file (update of include directives)
Note that though it's basic, it's rarely well dealt with. My primary complaint being that comments are generally not updated (I am so not speaking about doxygen auto-generated useless clutter). So if I was describing the use of the class within a header, or the justification of using this class in another source file, the comment is now obsolete because by renaming the class no one will now know what it refers to...
There are however much more interesting cases:
When changing a function signature, you need to update all the call sites, the developer will need help for localizing them
With inheritance, the ability to act on all classes of a hierarchy: changing a function signature (once again) or adding/removing a virtual override.
With template: the Concept proposal having been dropped, it would be good if you could synthetise the requirements on the type passed (methods / inner types necessary) so that when altering those requirements (by modifying the template definition) one gets notified of the list of classes that are in use by this template and no longer conform to it (and shall be updated). Note that in case it's just renaming the type / method, you might want to automatically propagate the change, as long as it doesn't break anything else.
Good luck...
Take a look in Martin Fowler's Refactoring: Improving the Design of Existing Code and Refactoring to Patterns by Joshua Kerievsky. These in turn reference the GoF Design Patterns book so get that too.
If you can beyond the basic Rename Feature and Extract Function then you might be onto a winner.
Here's a C++ design pattern I came up with yesterday: Ditch inheritance in favor of policies.
One refactoring that I wish was supported is actually inject method. More-or-less the opposite of extract method.
Because perhaps I see that I can then rearrange the resulting code to better clarity or effect; but I am not aware that there is tool support for this at present.
Hi i use http://www.devexpress.com/Products/Visual_Studio_Add-in/RefactorCPP/ with this tool i do renaming variable/class/method, changing function body,initializers