"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Does C++ built-in types really have default constructors?

Does C++ built-in types really have default constructors?

Posted on 2025-04-17
Browse:621

Do C   Built-in Types Really Have Default Constructors?

Do Built-in Types Have Default Constructors in C ?

Despite the statement in TC PL claiming that built-in types have default constructors, the answer in the context of C 03 is a nuanced "no."

Reasoning

Built-in types do not have declared constructors in the traditional sense. However, they can be initialized using a syntax that resembles constructor calls. This initialization appears as:

int x0(5); // Looks like a default constructor
int x1{5}; // New syntax for default initialization

While these expressions mimic constructor calls, they actually invoke value initialization. Value initialization is a mechanism that initializes primitive types to default values determined by their type.

Implications of Initialization Syntax

Although built-in types lack explicit constructors, the initialization syntax creates the illusion of default constructors. This is particularly evident with the new syntax for zero-initialization:

int z0 = int(); // Appears like a default constructor
int z1 = int{}; // New syntax for zero-initialization

These expressions behave similarly to default constructors, initializing variables to their default value (in this case, 0).

Bjarne Stroustrup's Clarification

When contacted regarding the apparent discrepancy in TC PL, Bjarne Stroustrup clarified that while built-in types do not have constructors in the conventional sense, they are conceptually considered to have constructors based on their initialization behavior.

Conclusion

In C 03, built-in types do not technically possess default constructors. Nonetheless, their initialization syntax creates the illusion of such constructors, allowing them to be initialized as if they did. This distinction highlights the nuance of C 's initialization mechanisms and the flexibility of its syntax.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3