I'm making thise database program and I have a class item. I need to call it with a name, price, amount and ID. For the ID i use int i as a side variable.
Yet, when I cal getId() it will ALWAYS be 15...
item(const string& naam, int prijs, int aantal, int id) : naam(naam), prijs(prijs), aantal(aantal), id(id)
{
}
Hi reference to the above initializer list, I read from Scott Meyers there is a catch to doing above syntax. The explanation is long but the idea is the ORDER you define above should CORRESPOND to the order they are declared in the class?!?! (Or maybe I read it wrongly)
clasclass item
{
private:
int id;
string naam;
int prijs;
int aantal;
...
}
Then your member initializer list must follow above order.
item(const string& naam, int prijs, int aantal, int id) : id(id), naam(naam), prijs(prijs), aantal(aantal)
{
}
Can anyone confirm on this? This was a reason till today I did not use initializer list also :(
In theory, you can have them in any order in the initializer list, however they will be initialized in the order they appear in the class.
So even if id stands at the end of the initializer list, it will be initialized first.
In theory, you can have them in any order in the initializer list, however they will be initialized in the order they appear in the class.
So even if id stands at the end of the initializer list, it will be initialized first.
Thanks a lot! Now I can use them with confidence! But to play safe, I better follow the order as recommended by Scott Meyers.
Above is important cuz usually in our constructor we do initialization and what if some initialization variables is dependent on other variables being initialized FIRST? So if we follow the above order we are guaranteed safety.
The order of the variables in the initializer lists does not matter - you cannot change the order of initializations by switching them around. If one initialization depends on the initialization of another object, you have to make sure the object it depends on is declared before it.
That being said, the order in the initializer list should of course match the order of declaration - but just for clarity, since it does not affect the program behavior at all.