I'm a C developer and I decided to move to c++ as main language to enlarge my horizons. Studying from "The C++ Programming Language" I saw this example of the creation of a class:
class Vector {
public:
Vector(int s) :elem{new double[s]}, sz{s} { }
double& operator[](int i) { return elem[i]; }
int size() { return sz; }
private:
double* elem;
int sz;
};
And I don't get the use of sz{s} { }
Why do we use the {}
? Why there is not ;
at the end of the line?
The last
{}
is the body of the constructor. Methods dont need a;
at the end. The stuff before is the initializer list:This could also be written as
but then the member are initialized and then assigned a value.
Because of lazy indentation. Let's write it clearer:
See? Your mysterious
{}
are just the body of the constructor, that is just a function body, and as in C, functions do not end with a;
.The weird lines beginning with
:
is the initialization list, where member variables and base classes are initialized, that is where you write the areguments to their constructors. Thesz{s}
is just the second element in this list.