Predict the output of following program?
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.
Thanks to Prasoon Saurav for initiating the discussion, providing various references and correcting lacuna in my understanding.
Contributed by Venki. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- The C++ Programming Language, 3e.
- Latest C++ standard – working draft section 8.5.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Does C++ compiler create default constructor when we write our own?
- Is body of a Default Constructor blank in C++?
- Builtin functions of GCC compiler
- Difference between fundamental data types and derived data types
- C++ Internals | Default Constructors | Set 1
- Templates and Default Arguments
- Default arguments and virtual function
- Default Assignment Operator and References
- When does compiler create default and copy constructors in C++?
- Some Interesting facts about default arguments in C++
- Default Arguments in C++
- Default values in a Map in C++ STL
- Default Methods in C++ with Examples
- Default value of Vector in C++ STL
- Copy constructor vs assignment operator in C++
- When is copy constructor called?
- When should we write our own copy constructor?
- What is conversion constructor in C++?
- Advanced C++ | Virtual Constructor
- Advanced C++ | Virtual Copy Constructor