By default C/C++ won’t initialize data for primitive types. So if you have an int or double etc. you have to explicitly initialize it if your code is expecting say an integer variable to start out with the value zero.
...
C/C++ was designed to allow for writing efficient code which is why it is like this but it’s a frequent ‘gotcha’ especially for developers that come from languages like Python and Java which always initialize new variables.
...
Best practice with member variables on classes is typically to initialize the data in the constructor of the class.
Code Block | ||
---|---|---|
| ||
void FOObar(){
int Position; // Position could be any value so you may get unexpected behaviour
int i = 0; // Probably more what you intended.
// Unnecessary and wasteful since default constructor is called
COLstring Value="";
// The following is better
COLstring Value;
}
class FOObling{
// This shows the best practice of initializing primitive members in the class
// constructor
FOObling() : m_Position(0) {}
private:
int m_Position;
}; |