Re: Constructors



Joerg Simon wrote:

I think the big difference here is, that in C++ you have copy-constructors, and in java not, because everything is on the heap.

And member variables are either reference (pointer) types or primitives. And simple classes are often immutable (or should be immutable).

Still, there are times when you need explicit defensive copies in Java. Receiving an array in a set method or returning one in a get method, for instance. In C++ the copy tends to be implicit.

C++: [pseudo, it has been a few months since my last c++ proj. and c# and java is just to different... @_@]
class Test1 {

A &a1_, &a2_;

// ctor
Test1(A &a1, A &a2): a1_(a1), a2_(a2) {}
}
;

Here you just copy references, so the difference to a variance with the copying in the body in not very big. Actually, that is, what you do in java.

In C++ you can't move reference initialisation into the constructor body:

class Test2 {
int &i;
Test2(int &x) {
i = x;
}
};

copyref.cpp: In constructor ‘Test2::Test2(int&)’:
copyref.cpp:3: error: uninitialized reference member ‘Test2::i’

The Java equivalent is:

class Test2 {
final int[] i;
Test2(final int[] x) {
i = x;
}
}

This works because of Java's concept of definitely initialised/uninitialised. In C++ variables are initialised effectively at point of declaration (possibly implicitly). In Java initialisation may happen later, if at all.

Tom Hawtin
--
Unemployed English Java programmer
http://jroller.com/page/tackline/
.



Relevant Pages

  • Re: Should I explicitly initialize all member variables?
    ... question is about member variables. ... There are a couple of slight errors in that, in the Java bit: ... reference type which is used for boxing the value type derives ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: final and const java help needed for an old C++ programmer
    ... the same in java. ... be changed after initialization," and for member variables it ... immutable objects. ... The JLS sets the rules in ...
    (comp.lang.java.help)
  • Re: final and const java help needed for an old C++ programmer
    ... the same in java. ... reference final just stops the reference being changed. ... be changed after initialization," and for member variables it ...
    (comp.lang.java.help)
  • Re: java websrvice and C# code file
    ... WSDL generate public access to member variable. ... You can add accessor get/set on generated file but it's not a good idea ... > I am trying to consume a Java webservice from .Net client. ... The java classes has member variables with get and set methods. ...
    (microsoft.public.dotnet.general)
  • Re: Explanation needed of binary operators
    ... I am trying to read an int from a file written in binary. ... binary data as an "archaic" file structure. ... int in Java but don't understand what is happening. ... Big-endian hardware stores bytes in memory in their "natural" format, ...
    (comp.lang.java.programmer)