13

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

dukevin
  • 22,384
  • 36
  • 82
  • 111
  • 3
    What sort of teaching material are you using that you get confused by these things? Pick up a decent book on C++, and this should be fairly straight-forward... – Kerrek SB Sep 29 '11 at 22:24
  • 1
    Teaching myself, that how it is now-a-days – dukevin Sep 29 '11 at 22:31
  • Worth noting that initialisation lists are initialised in the order that the variables are declared in your class and not the order they are declared in the list itself. – graham.reeds Sep 29 '11 at 23:01
  • 2
    For a decent book: [The Definitive C++ Book Guide and List](http://stackoverflow.com/q/388242/46642) – R. Martinho Fernandes Sep 29 '11 at 23:10

4 Answers4

18

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.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
5
Month(char first, char second, char third) 
      : first(first)
      , second(second)
      , third(third)
{} //DOES WORK :)
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434
4

As others have pointed out, it's just a comma seperated list of items. The variable(value) syntax is just a default way of constructing primative datatypes, you can use this method outside of initialization lists for example. In addition, if a member of your class is also a class with a constructor, you'd call it in the exact same way.

You are not only bound to putting the list in the declaration of the class, just for future reference. This code is perfectly fine 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
};
Anne Quinn
  • 12,609
  • 8
  • 54
  • 101
1

Initializers are comma-separated, and your constructor should have only one body.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174