Sunday 28 August 2011

Initialization lists and constructors in C++

class Foo
{
    const int someThing;
    const float nothing;
    public:
      Foo()
      {
         someThing = 5;
         nothing = 5.0;
      }


}


The above implementation is wrong as we have to initialize const and refrences in the same line where we declare them.


The above code is same as 
const in x;
x=5; 
which obviously the compiler will not let us do.


the solution for the above problem is we use implicit initialization using the initialization list.



class Foo
{
    const int someThing;
    const float nothing;
    public:
      Foo(): something(5),nothing(5.0)
      {


      }
}


The initialization list is inserted after the constructor parameters, begins with a colon (:), and then lists each variable to initialize along with the value for that variable separated by a comma. Note that we no longer need to do the explicit assignments in the constructor body, since the initializer list replaces that functionality. Also note that the initialization list does not end in a semicolon.

No comments:

Post a Comment