• C++ default constructor | Built-in types


      Predict the output of following program?

    1 #include <iostream>
    2 using namespace std;
    3  
    4 int main() 
    5 {
    6  
    7    cout << int() << endl;
    8    return 0;
    9 }

      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.

      具体更多内容请查看:http://www.geeksforgeeks.org/c-default-constructor-built-in-types/

      Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

      转载请注明:http://www.cnblogs.com/iloveyouforever/

      2013-11-26  19:08:38

  • 相关阅读:
    8.20Java之反射机制的基本概念
    8.18Go语言之字符串
    Debug
    Feign
    Nacos
    SpringCloud Alibaba
    SpringCloud
    Maven
    Maven
    Jenkins
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3443927.html
Copyright © 2020-2023  润新知