| Author |
class X that contains class X
|
Hendra Kurniawan
Ranch Hand
Joined: Jan 31, 2011
Posts: 239
|
|
I have a class like this:
At first glance, it should produce stack overflow when you allocate new X(), because everytime you call new X(), the constructor will call new X(), which in turn will call new X(), and so on. But when I tried running this, the code compiled and ran just fine. I don't get it. Could anybody explain this phenomenon? thanks
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4761
|
|
Hendra Kurniawan wrote:At first glance, it should produce stack overflow when you allocate new X(), because everytime you call new X(), the constructor will call new X(), which in turn will call new X(), and so on. But when I tried running this, the code compiled and ran just fine. I don't get it. Could anybody explain this phenomenon? thanks
Ah. That would be because 'x' is not an X, but an X[], which is something quite different. Change
for(int i=0;i<10;i++) x[i]=null;
to
for(int i=0;i<10;i++) x[i]=new X();
and you'll soon find out what I mean.
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
Jeff Verdegan
Bartender
Joined: Jan 03, 2004
Posts: 5895
|
|
Hendra Kurniawan wrote:I have a class like this:
At first glance, it should produce stack overflow when you allocate new X(), because everytime you call new X(), the constructor will call new X()
Nope. new X[len] is not the same as new X(). The former creates an array full of nulls, and does not create any X objects. And because of this, the for loop in the constructor is pointless, since all the array elements are initialized to null at array creation and only change when we explicitly set them.
|
 |
Hendra Kurniawan
Ranch Hand
Joined: Jan 31, 2011
Posts: 239
|
|
|
Ah, it's clear now. Thank you very much. Have a nice day!!
|
 |
 |
|
|
subject: class X that contains class X
|
|
|