Saturday, November 21, 2020

Virtual Constructor in C++

when I read "C++ Gems" book, there is one chapter mentioning this topic. so I did research and find many good articles. collected here for future reference.

  1. Advanced C++ | Virtual Constructor
  2. Can we make a class constructor virtual in C++ to create polymorphic objects? No. C++ being statically typed (the purpose of RTTI is different) language, it is meaningless to the C++ compiler to create an object polymorphically. The compiler must be aware of the class type to create the object. In other words, what type of object to be created is a compile-time decision from the C++ compiler perspective. If we make constructor virtual, compiler flags an error. In fact, except inline, no other keyword is allowed in the declaration of the constructor.

    In practical scenarios, we would need to create a derived class object in a class hierarchy based on some input. Putting in other words, object creation and object type are tightly coupled which forces modifications to extended. The objective of the virtual constructor is to decouple object creation from its type.

    How can we create the required type of an object at runtime? For example, see the following sample program.

  3. Virtual Constructor in C++
  4. The virtual mechanism works only when we have a base class pointer to a derived class object.

    In C++, the constructor cannot be virtual, because when a constructor of a class is executed there is no virtual table in the memory, means no virtual pointer defined yet. So, the constructor should always be non-virtual.

    But virtual destructor is possible.

  5. Why do we not have a virtual constructor in C++?
  6. More C++ Idioms/Virtual Constructor
  7. [20.8] What is a "virtual constructor"?
  8. Virtual constructor
  9. Inheritance — virtual functions ¶
  10. Inheritance — What your mother never told you
  11. In C++, why can’t a constructor be declared as virtual?
  12. virtual function specifier
  13. Virtual call from constructor or destructor
  14. FAQ: What is a "virtual constructor"?
  15. [20] Inheritance — virtual functions
  16. OOP50-CPP. Do not invoke virtual functions from constructors or destructors
  17. Inheritance
  18. Item 9: Never call virtual functions during construction or destruction.
  19. What are virtual functions?
  20. 12.3 — Virtual destructors, virtual assignment, and overriding virtualization
  21. why Can't we have virtual constructor but we have virtual destructor?
  22. C++ Calling (Pure) Virtual Members From Constructor Or Destructor
  23. Virtual Constructor in C++ and Java

No comments:

Post a Comment