Home > Backend Development > C++ > Why are Virtual Constructors Absent in C ?

Why are Virtual Constructors Absent in C ?

Barbara Streisand
Release: 2024-11-19 09:22:02
Original
415 people have browsed it

Why are Virtual Constructors Absent in C  ?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template