Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

This example code is from A tour of C++ book, please explain this code

In class vector, inside public those two three lines are written, Please explain the constructor function and also below two lines of code.

class Vector {
public:
Vector(int s) :elem{new double[s]}, sz{s} { } // constr uct a Vector
double& operator[](int i) { return elem[i]; } // element access: subscripting
int size() { return sz; }
private:
double∗ elem; // pointer to the elements
int sz; // the number of elements
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Vector(int s) :elem{new double[s]}, sz{s} { }

This {} is also used to assign or initialize data in variable.

Vector(int s) is a constructor which is allocating a dynamic array of size s and assigning address to pointer elem and also assigning s into the private variable sz.

double& operator[](int i) { return elem[i]; }

this function is returning reference to double and taking an int as argument and returning reference to the ith element of elem. *(elem + i)

int size() { return sz; }

size function is returning the private member sz, which is basically the size of the vector.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading