Monday, April 5, 2010

Interesting coding bug in C++ and JAVA

Hey while creating classes there are some interesing thing that may come up to you :)
Consider you are creating a class object inside the same class constructor. The program will surely eat up your stack. Let's see some code.

C++ let's call it Test.cpp:
class Test {
public:
Test() {
Test obj;
}
}

int main()
{
Test o;
}


When I compiled and ran the code it soon ended in a Segmentation fault :) you know why.

The "secure(cliche)" JAVA also not restricts the creation of object in the same class constructor so I also experimented with it so the results are

JAVA (say Test.java);
class Test {
Test() {
Test obj=new Test();
}

public static void main(String[] args)
{
Test o;
}
}


Compile and run come with with Exception StackOverflowError

On my machine when i checked C++ managed to create 163698 object then Segmentation fault
JAVA created 5818 objects and then Stack Overflow exception Oh my...
COOL
Which one is awesome?
comments

No comments:

Post a Comment