Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call a member function in a constructor

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(); }
like image 446
jabk Avatar asked Oct 20 '14 11:10

jabk


People also ask

Can I call member function inside constructor?

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.

Should you call methods in a constructor?

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.

Are constructors member functions?

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.


1 Answers

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

like image 81
Dr. Debasish Jana Avatar answered Nov 15 '22 05:11

Dr. Debasish Jana