I'm trying to learn how to initialize lists.
I have a simple class below and trying to initialize the list of variables. The first Month(int m): month(m)
works. I'm trying to do something similar below that line with more than one variable. Is this possible in that format? would I have to break away from the 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 don't have much clue how to do this, any guidance would be appreciated, thanks
Example - Declaring multiple variables in a statementIf your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.
Initializer List is used in initializing the data members of a class. The list of members to be initialized is indicated with constructor as a comma-separated list followed by a colon. Following is an example that uses the initializer list to initialize x and y of Point class.
Conclusion: All other things being equal, your code will run faster if you use initialization lists rather than assignment.
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.
Try this:
Month(char first, char second, char third)
: first(first), second(second), third(third) {}
[You can do this as a single line. I've split it merely for presentation.]
The empty braces {} are the single body of the constructor, which in this case is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With