C++ vs Java constructors

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

    There are particular cases in C++ where a constructor will not be called. In particular for POD types the implicitly defined default constructor will not be called in some situations.

    struct X {
       int x;
    };
    int main() {
       X x;        // implicit default constructor not called
                   //    No guarantee in the value of x.x
       X x1 = X(); // creates a temporary, calls its default constructor
                   //    and copies that into x1. x1.x is guaranteed to be 0
    }
    

    I don't quite remember the whole set of situations where that can happen, but I seem to recall that it was mostly in this case.

    To further address the issue:

    This is pointed as a Java peculiarity which makes it different from C++ in its behaviour. So I must argue that C++ in some cases does not call any constructor for a class even if an object for that class is created.

    Yes, with POD types you can instantiate objects and no constructor will be called. And the reason is

    This is of course done for compatibility with C.

    (as Neil comments out)

    I think that this happens when inheritance occurs, but I cannot figure out an example for that case.

    This has nothing to do with inheritance, but with the type of object being instantiated.

提交回复
热议问题