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?
Because of lazy indentation.
Let's write it clearer:
class Vector
{
private:
double* elem;
int sz;
public:
Vector(int s)
: elem{new double[s]}
, sz{s}
{
// ctor body
}
// More class members
};
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. The sz{s}
is just the second element in this list.
The last {}
is the body of the constructor. Methods dont need a ;
at the end.
The stuff before is the initializer list:
Vector(int s) :elem{new double[s]}, sz{s} { }
// ^^ initializer list ^^ body of the constructor
This could also be written as
Vector(int s) { // no initializer list, but still
// members are initialized here already
elem = new double[s];
sz = s;
} // no ; here !!
but then the member are initialized and then assigned a value.