Monday, May 16, 2011

Cpp vs Java in case of direct field initialization

In java, one can directly initialize instance fields of a class. See here for this.

But in C++, you cannot directly initialize instance fields of a class. All fields must be set in a constructor. However, C++ has a special initializer list sytax such as:

Employee::Employee(String n, double s, int y, int m, int d) // C++

: name(n),

salary(s),

hireDay(y, m, d)

{
//some other logic if needed
}

C++ uses this special syntax to call field constructors. In Java, there is no need for it because objects have no sub-objects, only pointers to other objects.

No comments:

Post a Comment

Chitika