C++ vs Java constructors

前端 未结 14 2463
一个人的身影
一个人的身影 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:19

    Trying to make things clear about C++. Lots of imprecise statements in answers.

    In C++, a POD and a class behave the same way. A constructor is ALWAYS called. For POD, the default constructor does nothing: it does not initializes the value. But it is an error to say that no constructor is called.

    Even with inheritance, constructors are called.

    class A {
      public: A() {}
    };
    
    class B: public A {
      public: B() {}   // Even if not explicitely stated, class A constructor WILL be called!
    };
    

提交回复
热议问题