M
Matthias Kaeppler
Hello,
I have decent knowledge of the C++ programming language, and I am
currently reading a book about Java ("Java in a Nutshell", 5th Edition,
O'Reilly).
I have a question concerning the construction of objects in Java. In
C++, the this-pointer is valid to use in the constructor body, because
C++ makes sure that when the ctor body is entered, the object has been
fully initialized to a default state, as defined by the constructor's
initializer list. This is a /good/ thing, because you are able to
provide your own initializer list, and may keep the compiler from
default-constructing a data member which value you would have hanged
anyway in the constructor (otherwise the object would have been
initialized twice, which is just brainless overhead and especially
expensive for complex user defined types).
Since Java does not have initializer lists, I can't imagine how this works:
public class Bar {
public Bar() {
this.a = 5; // which object does 'this' reference, when I
// am still in the state of initializing it?
}
}
I can only guess that the JVM takes care of default initializing each
data member before entering the constructor body, otherwise the
this-reference would reference an object which doesn't have a
well-defined state (and would probably lead to undefined behavior).
Is this true, and if this is the case, doesn't this imply a performance
hit to initialize every data member twice (in the worst case)?
Thanks in advance.
I have decent knowledge of the C++ programming language, and I am
currently reading a book about Java ("Java in a Nutshell", 5th Edition,
O'Reilly).
I have a question concerning the construction of objects in Java. In
C++, the this-pointer is valid to use in the constructor body, because
C++ makes sure that when the ctor body is entered, the object has been
fully initialized to a default state, as defined by the constructor's
initializer list. This is a /good/ thing, because you are able to
provide your own initializer list, and may keep the compiler from
default-constructing a data member which value you would have hanged
anyway in the constructor (otherwise the object would have been
initialized twice, which is just brainless overhead and especially
expensive for complex user defined types).
Since Java does not have initializer lists, I can't imagine how this works:
public class Bar {
public Bar() {
this.a = 5; // which object does 'this' reference, when I
// am still in the state of initializing it?
}
}
I can only guess that the JVM takes care of default initializing each
data member before entering the constructor body, otherwise the
this-reference would reference an object which doesn't have a
well-defined state (and would probably lead to undefined behavior).
Is this true, and if this is the case, doesn't this imply a performance
hit to initialize every data member twice (in the worst case)?
Thanks in advance.