Michael
Michael

Reputation: 5897

Calling other functions from a C++ constructor

Is it safe to call non-virtual functions, including the assignment operator, from the body of a constructor after all member variables have been initialized?

Upvotes: 0

Views: 103

Answers (2)

CreativeMind
CreativeMind

Reputation: 917

Yes, constructor can make call to non-virtual functions.

Make sure all members have been initialized properly before calling assignment operator otherwise object will be in an inconsistent state.

Use the "Virtual Constructor idiom" when you want to call virtual functions from constructor.

Upvotes: 1

Tony Delroy
Tony Delroy

Reputation: 106096

Yes - you can call other non-virtual member functions freely. You can call virtual functions if the most derived base class provides an implementation you happen to want.

Indeed, before C++11 let one constructor call another, it wasn't uncommon for several constructors to call a support function to perform shared initialisation.

operator= can be called in these circumstances - the crucial thing is that any clean-up it might attempt before assigning new state will find sane values to operate on - for example, pointers set to nullptr so delete is safe.

Note that any exceptions from other functions you call that are allowed to cause the constructor to exit (i.e. not caught and suppressed) will prevent the object coming into existence - same as for exceptions thrown directly from the constructor function.

Upvotes: 1

Related Questions