Avoiding Virtual Constructors in C : Insights from Bjarne Stroustrup
While object-oriented programming commonly utilizes virtual functions to enable polymorphism, C lacks the concept of virtual constructors. This peculiarity has perplexed many developers, leading to the question: Why is this feature absent in C ?
To delve into the reasoning behind this absence, let us seek the wisdom of C 's creator, Bjarne Stroustrup, who penned the following explanation in the C Style and Technique FAQ:
"A virtual call is a mechanism to obtain functionality when given partial information about an object. Specifically, virtual calls allow for calling functions even when aware only of interfaces and not the specific type of the object. However, creating an object requires complete information, particularly knowing the exact type of object to instanciate. Therefore, calling a constructor cannot be made virtual."
This logical reasoning explains why C does not have virtual constructors. Despite this limitation, Stroustrup's FAQ also offers a code snippet that provides an alternative way to achieve similar functionality without resorting to virtual constructors.
The above is the detailed content of Why are Virtual Constructors Absent in C ?. For more information, please follow other related articles on the PHP Chinese website!