I want to ask you for your best practices regarding constructors in C++. I am not quite sure what I should do in a constructor and what not.
Should I only use it for
Simple answer: it depends.
When designing your software you should might want to program via the RAII principle ("Resource Acquisition is initialization"). This means (among other things) that the object itself is responsible for its resources, and not the caller. Also, you might want to familiarize yourself with exception safety (in their different degrees).
For example, consider:
void func() { MyFile f("myfile.dat"); doSomething(f); }
If you design the class MyFile
in the way, that you can be sure before doSomething(f)
that f
is initialized, you save a lot of trouble checking for that. Also, if you release the ressources held by f
in the destructor, i.e. close the file handle, you are on the safe side and it is easy to use.
In this specific case you can use the special properties of constructors:
virtual
methods, you should not call those from inside the constructor, unless you know what you are doing -- you (or later users) might get surprised why the virtual overriding method is not called. Best not to confuse anyone.A constructor must leave your object in a usable state. And because it is aways wise to make it difficult to use your API wrong, the best thing to do is make it easy to be used correct (sic to Scott Meyers). Doing initialization inside the constructor should be your default strategy -- but there are always exceptions, of course.
So: It is a good way to use constructors for initialization. It is not always possible, for example GUI frameworks often need to be constructed, then initialized. But if you design your software completely in this direction, you can save a lot of trouble.