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

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.

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.

Inheritance Pattern [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am finding my naming conventions rather bothersome. I seem to be re-using the child specific names too much. In my Example below, I have a Widget which has-a Connection which has-a Config. Each of these objects has specialized classes for Foo and Bar types.
So my FooWidget has-a Foo-Connection which has-a Foo-Config. The same for Bar. In C++ I've ended up with nine different header files.
widget.h
connection.h
config.h
foo_widget.h
foo_connection.h
foo_config.h
bar_widget.h
bar_connection.h
bar_config.h
I cant help but look at this a feel like it isn't right. My instincts tell me something needs to be changed. It's like there is a design pattern somewhere to be taken advantage of. But I can't find a better solution.
So I guess my question is the following: Is there a design pattern that will improve this design?
-- I am having difficulty wording my question correctly. Please excuse me, I will update as the question itself becomes more clear.
I don't think there is anything wrong with the structure of your classes but without seeing what these classes do it is going to be hard to give advice on how to improve your design.
I think it is good style to have one header file per class. It makes things easier to find and you can easily use directories (or filters in your IDE) to organise your files. For example you may find it easier to structure your files:
|--Foo
|--foo_widget.h
|--foo_connection.h
|--foo_config.h
|--Bar
|--bar_widget.h
|--bar_connnection.h
|--bar_config.h
|--widget.h
|--connection.h
|--config.h
First of all, there's nothing wrong with doing things that way. Many like to put one class per header, in general. If you don't like looking at so many headers you might organize them by directory, or project tree filter, etc.
This is all a question of style. As long as functionality is untouched, the best option is a function of that funny feeling you have, and same for the folks supporting your code down the road. Maybe this answer can make that funny feeling go down for you, or maybe not.
Second, this very much depends on the use of each class. If the Foo and Bar classes are small, they can be put in the header that contains the encapsulating class. Perhaps add a forward declaration for the sake of the parent class, and finish declaring it at the bottom of the header. Bonus points if they're all related (for example FooConnection is a subclass of Foo) because this shortens declaration space.
If they're relatively small classes, there may be no harm in declaring the Foo and Bar classes within the definition their base class. Then there is no FooConnection--it's actually a Connection::FooConnection. In this case Connection doesn't just define the base for FooConnection, it owns its very definition. That means every time you use a FooConnection in your code, you are thinking in the context of a Connection. I rarely do this myself, primarily because I don't like typing Connection:: all the time, but also because there are so few cases where I only use a class in one context.
If the encapsulated classes are protected or private, then they're only used by the parent class itself (and friend classes and maybe subclasses, what have you). Then, since limited context is established, and if the class declarations are small (<50 or <100 lines), you can declare FooConnection and BarConnection within Connection and still maintain readability.
Bonus point: if you do end up declaring classes inside classes, you might take advantage of namespace separation. I don't know the uses of these classes, but I'm guessing FooConnection isn't a connection itself, but a Foo that belongs to a Collection. So then you might declare a Foo and a Bar class for each of Widget, Connection, and Config.

Why do developers split every single part of a software into so many modules? [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
I'm having a read of other people's source code from open source projects such as Pidgin, Filezilla and various others so that I may get a brief idea how software really is written.
I noticed that when writing GUI, they like to split the whole interface into classes.
More or less, lots of projects I see every single bit broken down, into perhaps a total of 70 files (35cpp and 35.h).
For example: 1 listview may be an entire class, a menubar may be a class or a tabview a whole module.
And this isn't just the UI part - the network modules are also broken down by a huge amount - almost every function itself is a .cpp file.
My question: Is this really just preference or does it have any particular benefit?
I for example would've written the whole UI into a single module..
What is the actual reason?
Some languages encourage one file per type, and people who know those languages also program in c++, and bring that habit here.
For reuse, you want thing you put into a header to be simple, orthogonal, and conceptually clean, this tends to mean avoiding files that have everything one particular project needs.
Before git/mercurial it could be a real hassle to have multiple people edit the same file. Thus separating things into lots of files help a lot with multiple people editting, both for the edits and for your version control software.
It also speed up compilation. The small the file you are editting, the less compilation is needed, so unless the linking stage is slow, small file is a very good thing.
Many people have been hurt by cramming things into a single or small numbers of files. Few people have been seriously hurt by chopping them up into 50+ files. People tend towards things that dont overtly teach you hard lessons.
you might want to split the project into separate files to improve readability and to sometimes also make debugging easier. The filezilla project could have all been written into just two files something like main.cpp and main.h but if you do that, you will have to write tens of thousands of codes into the same file which is a very bad programming practice even though it is legal.
One benefit will come from Testing. Distributing system testing throughout the design hierarchy (e.g. rather than a single physical component) can be much effective and cheaper than testing at only the highest-level interface.

Should I put classes in separate files in C++? [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 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.

Is nesting namespaces an overkill? [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 5 years ago.
Improve this question
I'm writing a C++ program that has a large number of classes. In my head I can visualise them as distinct collections. For example there's a collection of classes for reading and storing config data, and another collection for drawing a user interface with various widgets.
Each of those collections could be neatly stored inside separate namespaces, which seems sensible. The config part has a "screen" class, and the GUI part also has a "screen" class, but they are different to each other. I could rename one "gui_screen" and the other "config_screen", but that's the point of a namespace isn't it? To remove these prefixes we invent to separate things.
Part of me then thinks it'd be tidy to store those namespaces inside one main one so that none of my code can interfere with the namespaces of anything else. And I suppose it might also make the code more readable too.
Or am I just making overly complex hierarchies of data for no reason at all?
If you're having namespaces with common names such as "gui" and "config", and it's possible that your code may in the future be part of a library meant to be linked with other code not under your control, it might indeed be a good idea to nest all of "your" namespaces into a single named one (which probably should have no other content except the nested namespaces) which identifies them as "yours". There is really no penalty for doing so, especially if, as you think, it can be done in a way that helps readability. (That's quite different from deep nested hierarchies of class inheritance, which can definitely hamper clarity, as different functionality is added at each layer and a reader or maintainer of the code has to be jumping around among many files to see or change what's added where!-)
No, IMO you're not overdoing at all.
And resist the temptation to use using declarations or (heaven forbid!) using directives! It takes very little getting used to always typing all namespaces and, once you're used to it, it makes the code much easier to read and understand. ("Which screen type is this again, gui or config?")
Personally I've never seen more than two levels of namespace nesting that was at all meaningful or useful. What you've described sounds fine, but I wouldn't go any deeper than project::component unless you've got a tangible, demonstrable, "this breaks without it" reason to do so. In other words, foo::bar::screen is reasonable, foo::bar::ui::screen is highly questionable, and anything more than that almost certainly introduces more complexity than is justified.
It is not overkill. It is reasonable to nest your namespaces, e.g. piku::gui::screen etc.
You could also collapse them to piku_gui_screen, but with the separate, nested namespaces you get the advantage that, if you're inside piku::gui, you can access all names in that namespace easily (e.g. screen will automatically resolve to piku::gui::screen).
Defining namespaces you are not doing any hierarchy, so I don't see what the problem is, anyway namespace are there just to solve your very problem.
I personally love to group files/classes by their functionality. I normally start with a folder with a name that matches the namespace I will use. Eventually if a namespace needs to be reused in another application, you can easily take it out and build it into it's own dll and share it.
It also makes for nice intellisense so that when I'm drilling down through namespaces, I can see just the classes that are part of that group of functionality.
It seems to me that one namespace per developer ought to be enough -- you (presumably) have control over all the type names you define in your own code, and it's unlikely that you'll want to use the same type name for different types within the same project.
I think the main use of namespaces is to handle the case where two independent developers happened to choose the same type name -- without namespaces you'd have no way to use both developers' code in the same project. Multiple namespaces within a single developer's codebase, OTOH, just add complexity and typing overhead, with little or no compensating benefit.
All IMHO, of course.