C++ default constructor | Built-in types

C++默认构造函数与int()示例
本文探讨了C++中默认构造函数的概念及其使用,并通过一个简单的int()函数调用示例来说明其行为。解释了如何将int()视为一种概念上的构造函数调用,以及它如何在程序中打印出0。

Predict the output of following program?

#include <iostream>
using namespace std;

int main() {

   cout << int() << endl;
   return 0;
}

A constructor without any arguments or with default values for every argument, is treated as default constructor. It will be called by the compiler when in need (precisely code will be generated for default constructor based on need).

C++ allows even built-in type (primitive types) to have default constructors. The function style cast int() is analogous to casting 0 to required type. The program prints 0 on console.

The initial content of the article triggered many discussions, given below is consolidation.

It is worth to be cognizant of reference vs. value semantics in C++ and the concept of Plain Old Data types. From Wiki, primitive types and POD types have no user-defined copy assignment operator, no user-defined destructor, and no non-static data members that are not themselves PODs. Moreover, a POD class must be an aggregate, meaning it has no user-declared constructors, no private nor protected non-static data, no base classes and no virtual functions.

An excerpt (from a mail note) from the creator of C++, “I think you mix up ‘actual constructor calls’ with conceptually having a constructor. Built-in types are considered to have constructors”.

The code snippet above mentioned int() is considered to be conceptually having constructor. However, there will not be any code generated to make an explicit constructor call. But when we observe assembly output, code will be generated to initialize the identifier using value semantics. For more details refer section 8.5 of this document.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值