C ++ initialization lists for multiple variables

I am trying to learn how to initialize lists.

I have a simple class below and am trying to initialize a list of variables. The first Month(int m): month(m) works. I am trying to do something similar below this line with more than one variable. Is this possible in this format? would I have to tear myself away from one liner?

 class Month { public: Month(int m) : month(m) {} //this works Month(char first, char second, char third) : first(first){} : second(second){} : third(third){} //DOES NOT WORK Month(); void outputMonthNumber(); //void function that takes no parameters void outputMonthLetters(); //void function that takes no parameters private: int month; char first; char second; char third; }; 

Obviously, I do not know how to do this, any recommendations will be appreciated, thanks

+6
source share
4 answers

Try the following:

  Month(char first, char second, char third) : first(first), second(second), third(third) {} 

[You can do this as a single line. I only split it into a presentation.]

Empty curly braces {} is the only body of the constructor, which in this case is empty.

+9
source
 Month(char first, char second, char third) : first(first) , second(second) , third(third) {} //DOES WORK :) 
+5
source

As others have pointed out, this is just a comma-separated list of items. The syntax variable(value) is just a way to create primitive data types by default, you can use this method outside of initialization lists, for example. Also, if a member of your class is also a class with a constructor, you would name it in exactly the same way.

You are not only required to put the list in the class declaration, but only for future reference. This code is great for example

 class Calender{ public: Calender(int month, int day, int year); private: int currentYear; Time time; }; Calender::Calender(int month, int day, int year) : currentYear(year), time(month, day) { // do constructor stuff, or leave empty }; 
+3
source

Initializers are separated by commas, and your constructor should have only one body.

0
source

Source: https://habr.com/ru/post/898324/


All Articles