Bowen Fu
Bowen Fu

Reputation: 195

Can virtual function be called inside member initializer lists?

effective c++ item 9

Can function createLogString be virtual?

class BuyTransaction: public Transaction {  
 public:  
  BuyTransaction( parameters ):Transaction(createLogString(parameters)) { ... }
  ...   
 private:  
  static std::string createLogString( parameters );  
}; 

Upvotes: 3

Views: 267

Answers (1)

Yes, it can be virtual (instead of static). It will still be statically bound during construction however, and not dispatched dynamically.

The only point to making it virtual is if it is also used in some other member of the class (that is not a constructor/destructor) and a deriving class can possibly override it to do something useful for those members. However, that starts having the faint traces of a design smell.

Scott's advice of "Never call virtual functions during construction or destruction" stems from the fact that it rarely if ever accomplishes anything useful.

Upvotes: 5

Related Questions