I know it's a rather a simple question and also depends on the rest of the code, but I'm more interested in the rule of thumb.
So in what cases it's appropriate to call a function inside a constructor?
What is preferable:
ClassA obj1;
obj1.memFun();
or
ClassA obj1;
//where constructor of ClassA is
ClassA::ClassA(){ memFun(); }
The problem with calling virtual member functions from a constructor is that a subclass can override the function. This will cause the constructor to call the overridden implementation in the subclass, before the constructor for the subclass part of the object has been called.
You shouldn't: calling instance method in constructor is dangerous because the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on testability.
A constructor in C++ is a special 'MEMBER FUNCTION' having the same name as that of its class which is used to initialize some valid values to the data members of an object. It is executed automatically whenever an object of a class is created.
It's no harm to call a member function within your constructor. However, make sure the member function is non-virtual one, as dynamic binding mechanism starts after constructor is done. If memFun
is virtual and overridden in its subclass, then calling memFun
will bind to ClassA::memFun
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With