Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Current »

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.

However if you have a user defined type like COLstring etc. then the “default constructor” is called by the compiler. That makes it extra confusing.

Best practice with member variables on classes is typically to initialize the data in the constructor of the class.

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;
};

  • No labels