Re: Constructors
- From: Thomas Hawtin <usenet@xxxxxxxxxxxxxxxxx>
- Date: Mon, 29 May 2006 21:17:34 +0100
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/
.
- References:
- Constructors
- From: crazy.marc@xxxxxxxxx
- Re: Constructors
- From: Allan M. Bruce
- Re: Constructors
- From: crazy.marc@xxxxxxxxx
- Re: Constructors
- From: Allan M. Bruce
- Re: Constructors
- From: crazy.marc@xxxxxxxxx
- Re: Constructors
- From: Bjorn Abelli
- Re: Constructors
- From: Joerg Simon
- Constructors
- Prev by Date: JComboBox Arrays not working
- Next by Date: Re: converting some VB code to Java..
- Previous by thread: Re: Constructors
- Next by thread: Re: Constructors
- Index(es):
Relevant Pages
|
|