Re: Should you perform complex tasks in the constructor?
On 1/10/2013 4:54 PM, Chicken McNuggets wrote:
I've seen various arguments against this primarily centring on the fact
that the only way to return errors in a constructor is to throw an
exception. Of course exceptions seem to be a somewhat controversial
subject in the C++ community so I'll try and avoid touching on that.
But I have a couple of classes that are created when the program
launches and are freed just before the program terminates. It makes
sense for me to put a lot of logic in the constructor as these classes
are initialised from data in different configuration files which are
passed as command line arguments.
Is there any reason I shouldn't put all the file loading / reading /
storing of data in the constructor? Or would you not consider this a
problem? For reference I'm using libxml2 for reading the data in the
configuration files.
IMHO your question is a bit too general, which basically means the
answer to it is "there can be lots of things". For instance, putting
too much processing into constructors of some global data objects can
stretch the startup of a UI-driven application, and that's usually
frowned upon. At the same time if the application cannot function
without those objects fully set up, then it has to complete the
initialization whether it's in the constructor or elsewhere, so in that
case it probably doesn't really matter... What other reasons are there?
I can probably think of several. What if after some time you decide
to introduce some other initialization, and it has to be done before
your initial procedure? Do you create another global object and
construct that (and put the new initialization there)? You can run into
the problems connected to the order of things being initialized at
different times on different runs. What if that initialization has to
be conditional or have parameters that it reads from some other place?
So, think of maintenance of your code, not just of writing it... There
are probably other ones as well.
V
--
I do not respond to top-posted replies, please don't ask