Reputation: 1458
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(); }
Upvotes: 5
Views: 9991
Reputation: 795
Conceptually it might not be the best to call a public member functions in the constructor as it implies that the constructor is doing more than initialization and creation of the object. However, having the private member functions should be fine as they are not part of the interface of the class and can be considered as helper functions to the constructor.
Upvotes: 1
Reputation: 1257
In case memFun
is virtual and you do need to call it for your object to be completely built, consider using a factory method. Something like:
static ClassA* makeX(){
ClassA* pObj = new ClassX(); // ClassX is a subclass of ClassA.
pObj->memFun();
return pObj ;
}
Then make ClassA and ClassX constructors protected.
Upvotes: 2
Reputation: 1863
It is usually safe to call any member function from within a constructor because the object has been completely set up prior to the execution of the first line of user code. However, it is potentially unsafe for a member function to call a virtual member function for an abstract base class during construction or destruction.
http://msdn.microsoft.com/en-us/library/s8e39b8h.aspx
Upvotes: 2
Reputation: 77285
A constructors task is to create an object in a valid, usable state. So if your function call is needed for the object's instance to be valid, please call it in the constructor.
Do not call virtual
methods in your constructor though, it can lead to problems.
Upvotes: 4
Reputation: 7118
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
Upvotes: 13