0

I am reading "Design Patterns" by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides. In chapter of factory method, there's one paragraph:

"Factory method in C++ are always virtual functions and are often pure virtual. Just be careful not to call factory methods in the Creator's constructor - the factory method in the ConcreteCreator won't be available yet."

I don't understand why the factory method in ConcreteCreator won't be available yet? is it because C++ is a compiled language therefore the method of the children class won't be available as the parent class is compiled first? Thank you.

rawrex
  • 4,044
  • 2
  • 8
  • 24
Nigel
  • 161
  • 12
  • 1
    `Creator`'s constructor is executing _before_ `ConcreteCreator` has completely come into being. Thus anything that is part of `ConcreteCreator` is not available to `Creator`, including virtual function implementations. – jkb Feb 08 '22 at 05:17
  • so that's what happened in run-time when someone called creator right? @jkb – Nigel Feb 08 '22 at 05:19
  • 1
    This is the case when someone instantiates a `ConcreteCreator` object. When that happens, the base class (`Creator`) constructor is invoked first, then `ConcreteCreator`'s. Because of this, you want to be sure that while you're in the `Creator` constructor you don't try to call any virtual functions that might be defined in any derived classes. – jkb Feb 08 '22 at 05:38

0 Answers0