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 attribute initializations, calling parent constructors etc.?
Or might I even put more complex functions into them like reading and parsing configuration data, setting up external libraries a.s.o.
Or should I write special functions for this? Resp. init() / cleanup()?
What are the PRO’s and CON’s here?
I figured out yet that for example I can get rid of shared pointers when using init() and cleanup(). I can create the objects on the stack as class attributes and initialize it later while it is already constructed.
If I handle it in the constructor I need to instantiate it during runtime. Then I need a pointer.
I really don’t know how to decide.
Maybe you can help me out?
Complex logic and constructor do not always mix well, and there are strong proponents against doing heavy work in a constructor (with reasons).
The cardinal rule is that the constructor should yield a fully usable object.
It does not mean a fully initialized object, you may defer some initialization (think lazy) as long as the user does not have to think about it.
If there is heavy work to be done, you might choose to proceed with a builder method, that will do the heavy work prior to calling the constructor. For example, imagine retrieving settings from a database and building a setting object.
This builder method is useful if postponing the construction of the object yields a significant benefit. From example if the objects grab a lot of memory, postponing the memory acquisition after tasks that are likely to fail may not be a bad idea.
This builder method implies Private constructor and Public (or friend) Builder. Note that having a Private constructor imposes a number of restrictions on the usages that can be done of a class (cannot be stored in STL containers, for example) so you might need to merge in other patterns. Which is why this method should only be used in exceptional circumstances.
You might wish to consider how to test such entities too, if you depend on an external thing (file / DB), think about Dependency Injection, it really helps with Unit Testing.