Can I get some help with explanation of the following code?
#include <iostream>
class Vector {
private:
double∗ elem; // pointer to the elements
int sz; // the number of elements
public:
Vector(int s) :elem{new double[s]}, sz{s} { }
double& operator[](int i) { return elem[i]; }
int size() { return sz; }
};
I am trying to brush up my C++ knowledge, but this syntax seems very new to me.
More specifically the code under public
.
It is the constructor. It is required an int parameter for instantiating.
This part describes how to initiate the member variables. An array type of double named elem. emem has "s" length array. sz is set as "s".
This part is in order for access by element index.
I will share an example. This is introduced in The C++ Programming Language (4th Edition) written by Bjarne Stroustrup
Maybe it's the new C++11 initialisation-lists that are confusing you, you now can initialise a variable with curly-braces
{}
. For example:everything else in your code looks pretty standard pre-C++11
Vector(int s)
defines a constructor - a special method that is called when object is created.:elem{new double[s]}, sz{s}
is a initializer list - it initializes object's fields. The whole part:Works same as
However, initializer lists can be used to initialize constants and references.