Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ initialization lists for multiple variables

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

like image 317
dukevin Avatar asked Sep 29 '11 22:09

dukevin


People also ask

Can you initialize multiple variables in the same line C?

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.

What is initialization list in C?

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.

Is initialization list faster?

Conclusion: All other things being equal, your code will run faster if you use initialization lists rather than assignment.

Which of the following is used to initialize multiple variables with a common value?

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.


1 Answers

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.

like image 99
Andy Thomas Avatar answered Sep 20 '22 10:09

Andy Thomas