In fact, this is one of the important differences between C + + and Java. The C + + compiler does not initialize local variables, so it is easy to forget to initialize a variable in C + +, in which case the value of the variable is exactly the current random value in the memory area. This is obviously where the program is prone to error.
Like Java, classes in C + + can have data fields and static variables. The difference is that variables in C + + can be defined outside of a function or even a class, and these so-called global variables can be accessed in any function of the program and therefore not easily managed. You should try to avoid using global variables in C + +.
In C + +, constants can be defined anywhere (remember in Java, constants must be static data for classes). C + + uses the keyword const to define constants, while in Java it is final. For example:
const int days_per_year = 365;
The definition of a class in C + + is somewhat different from Java, here is an example: a C + + version of the Point class:
Class Point/* C + + *
{
Public
Point ();
Point (Double xval, double yval);
void move (double dx, double dy);
Double GetX () const;
Double GetY () const;
Private
Double X;
Double y;
};
Here are a few important differences:
1. The class definition for C + + is divided into public and private parts, starting with the key, common, and individual. In Java, each element must be marked public or private.
2. The definition of a class in C + + contains only the declaration of the function, and the true implementation is separately listed.
3. The Access function (accessor methods) is marked with the keyword const , which indicates that the function does not change the element value of this object.
Variables and Constants in C + + and Java