C++ Class Initialization List example

Jasmine picture Jasmine · Jun 2, 2013 · Viewed 11.8k times · Source

I am going through Chapter 17 in the new Stroustrup book and I am confused by initializing a class with an initialization list.

Example:

in .hpp:

class A
{
    public:
        A() : _plantName(std::string s), _growTimeMinutes(int 1);
        virtual ~A();

    private:
        std::string _plantName;
        int _growTimeMinutes;
};

in .cpp:

A::A() : _plantName(std::string s), _growTimeMinutes(int i)
{

}

or is it in .cpp:

A::A(std::string s, int i) : _plantName(std::string s), _growTimeMinutes(int i)
{

}

and calling that:

A a {"Carrot", 10};

I learned c++ back in 1998 and have only programmed in it off and on over the years until recently. How long ago did this stuff change? I know I could still do that the older way but I really want to learn new!

Answer

Silouane Gerin picture Silouane Gerin · Jun 2, 2013

First I think initialization lists are useful when when you are dealing with constant members or when passing objects as parameters since you avoid calling the default constructor then the actual assignement.

You should write the following code in your cpp file : no need to rewrite the parameters types in the initialization list.

A::A(std::string s, int i) : _plantName(s), _growTimeMinutes(i)
{
}

Your h file should be :

class A
{
    public:
         A(std::string, int);
    private:
        std::string _plantName;
        int _growTimeMinutes;
};

And you should create a new A object like that

A new_object("string", 12);