C++ vs Java constructors

前端 未结 14 2478
一个人的身影
一个人的身影 2021-02-09 20:31

According to John C. Mitchell - Concepts in programming languages,

[...] Java guarantees that a constructor is called whenever an object is created.

14条回答
  •  心在旅途
    2021-02-09 21:36

    Java constructors can call another constructor of the same class. In C++ that is impossible. http://www.parashift.com/c++-faq-lite/ctors.html

    POD's (plain old data types) are not initialized via constructors in C++:

    struct SimpleClass {
        int m_nNumber;
        double m_fAnother;
    };
    
    SimpleClass simpleobj = { 0 }; 
    SimpleClass simpleobj2 = { 1, 0.5 }; 
    

    In both cases no constructor is called, not even a generated default constructor:

    • A non-const POD object declared with no initializer has an "indeterminate initial value".
    • Default initialization of a POD object is zero initialization. ( http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html )

    If however, SimpleClass itself defined a constructor, SimpleClass would not be a POD anymore and one of the constructors would always be called.

提交回复
热议问题