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!
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.
Your h file should be :
And you should create a new A object like that
It should be
for example
supposing the variables _plantName and _growTimeMinutes are declared within class A or one of its superclasses. s and i are the constructor parameters for class A, the initialization will then call the string-constructor for _plantName with argument s and the int-constructor for _growTimeMinutes with argument i, thus initializing both variables.
Initialization lists are especially needed if you want to initialize const references. The assignment within a constructor would not work.
Hope I could help