3

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 );  
}; 
Bowen Fu
  • 165
  • 8
  • Possible duplicate of [Calling virtual functions inside constructors](https://stackoverflow.com/questions/962132/calling-virtual-functions-inside-constructors) – Alan Birtles Jan 22 '19 at 08:15
  • It's not allowed to have both `static` and `virtual`, so here we all assume that you want to change the static function into a virtual function. – Bentoy13 Jan 22 '19 at 08:42

1 Answers1

5

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.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458