0

Possible Duplicate:
What is this weird colon-member syntax in the constructor?

I'm trying to understand what this kind of code means

Say I have this

class OptionStudent: public Student // derived class from Student class
{
    public:
        explicit OptionStudent(const std::string id = "12345678", 
                               const std::string first = "someone")
        : Student(id, first)
        {
             count_++;
        }
}

What is that colon after the "someone"): <-- part called or mean for this constructor?
I know the constructor may be a little incorrect but I don't know what this is called. I just copied my notes from what the instructor was writing on the board and didn't understand it.
Something to do with the class or object remembering something?

Community
  • 1
  • 1
Kevin Heng
  • 173
  • 1
  • 3
  • 10

2 Answers2

1

It is the member initialization list. In this case, it calls the base class's constructor with id and first as arguments. It could also provide initial values for non-static data members of your class (if you had any).

Note that the semicolon after Student(id, first); is a syntax error and needs to be removed.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • ah thanks! and yes it should be a comma for further elements i just realized that in my notes for further members, got into a habit of the other constructor. placed the semicolon out of habit. I didnt knwo it was called an initialization list thank you. – Kevin Heng Nov 26 '12 at 12:32
0

It is called an "initialization list". See following article "Understanding Initialization Lists in C++".

The basic idea is that when you enter the code of constructor after { you should have all members initialized to values passed as arguments or default.

Using initialization lists you can also pass arguments directly to base class too! This is what is happening in example you are describing:

  • first, both id and first are set to some values using default parameter value.
  • second, these values are used to initialize base Student class.

Of course one can pass different values as OptionStudent arguments and these values would be used to initialize Student.

Marcin Gil
  • 68,043
  • 8
  • 59
  • 60