Open In App

C++ default constructor | Built-in types for int(), float, double()

Improve
Improve
Like Article
Like
Save
Share
Report

A constructor without any arguments or with default values for every argument is treated as the default constructor. C++ allows even built-in types (primitive types) to have default constructors. The function style cast int() is analogous(similar in some way) to casting 0 to the required type.
It will be called by the compiler when in need(precisely code will be generated for the default constructor based on need).

Predict the output of the following program

C++




// C++ Program to demonstrate the working of a default
// constructor
#include <iostream>
using namespace std;
 
int main()
{
    cout << int() << endl;
    cout << float() << endl;
    cout << double() << endl;
 
    return 0;
}


Output

0
0
0

The time complexity of this program is O(1) 

The auxiliary space used by this program is also O(1)

The program prints 0 on the console. The initial content of the article triggered many discussions, given below is consolidation. It is worth being cognizant of reference v/s value semantics in C++ and the concept of Plain Old Data(POD) types.

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. The code snippet above-mentioned int() is considered to conceptually have a 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.

Must see articles on constructors;-

  1. Default constructors in C++
  2. Constructors in C++
  3. Copy constructors in C++

Last Updated : 27 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads