0

Good evening!

I was reading through Programming: Principles and Programming Using C++ and I found this piece of example code that really interested me during function initialization. For the C++ programmers that have been using C++ for a while, how does using this function initialization syntax help? Does it help your workflow, is it more readable to the programmer, or is just just another secret way of doing stuff in C++? Does it help with program performance?

I'd like to know about it some more and I couldn't find anything on it using my poor google skills.

class Year {
static const int min = 1800;
static const int max = 2200;

public:
class Invalid {}; //this thing throws an error when called
Year(int x) : y(x) { if (x < min || max <= x) throw Invalid(); } //what is : ??
int year() { return y; }

private:
int y;
};

2 Answers2

1

In this case : is the syntax used for an initializer list. An initializer list lets the constructors for the elements of the class be called without calling the default constructors then assigning to them.

You could rewrite the constructor as

Year(int x) : 
            ^ Indicates start of initializer list
    y(x) 
    ^^^ Initializes Y
{
    if (x < min || max <= x) throw Invalid();
}

You can read more about initializer lists here.

phantom
  • 3,292
  • 13
  • 21
0

It is an initializer list. It initializes values of the object being constructed.

MuertoExcobito
  • 9,741
  • 2
  • 37
  • 78