Friday, March 24, 2006

Data Member Initialization in Java and C++

If there is one thing I love about Java - then it is the data member initialization. You can initialize the data member right when you declare it. Unlike in C++, you have to initialize it in the constructor.

For example in C++ I would do something like this:

class A
{
private:
int i;

public:
A() { i = 0; }
...
...
~A() {}
};

In Java, I would do the same as follows:

public class A
{
private int i = 0;
A() { ... }
}

This is a very simple example and you wouldn't know the difference of the two, but think about a complex project when you have to scroll up and down to look at member variables declarations and their respective defintions in the constructors. Life would have been so much more simpler if languages stuck to one semantic.

0 Comments:

Post a Comment

<< Home