-4

I just don't really understand what's going on here(The constructing a new vector part). It's code from a book I am using to learn C++. I can't seem to find that sort of construction anywhere on the web.

class Vector 
{

public:
    Vector(int s):elem{new double[s]}, sz{ s }{}    //constructs a new vector
    double& operator[](int i) { return elem[i]; }   //elements access: subscripting
    int size() { return sz; }



private:
    double* elem; //pointer to the elements 
    int sz; // number of elements


};
ClarkKent
  • 1
  • 1
  • Doesn't the book explain it? Not a very good book if i just throws code at you without explanation. – john Jul 05 '19 at 06:06
  • 1
    So you don't understand the constructor initializer list? If the book uses it, it should have explained it before, or else it's not a very good book (perhaps consider getting [another book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282)?). And can you please be more specific about what parts of the constructor you don't understand? – Some programmer dude Jul 05 '19 at 06:06
  • 2
    Amazing duplicate, it's clearly the same code from the same book (and presumably the same lack of explanation in the book). I'd be interested to know what book. – john Jul 05 '19 at 06:27
  • I am also interested into which book this is. – Anže Jul 05 '19 at 07:34
  • The book is A Tour of C++ by Bjarne Stroustrup. Chapter 2.3 Classes. – ClarkKent Jul 06 '19 at 07:59

1 Answers1

1

So this code

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

is more or less the same as

Vector(int s)
{
    elem = new double[s];
    sz = s;
}

The first difference is that the books code uses an initialiser list instead of assignment to give values to the class variables. The advantage of an initialiser list is that it initialises the variables directly by calling the appropriate constructor. The alternative form first default constructs the variables and then assigns to them, a two step process which is potentially less efficient. But in your case the variables are a pointer and an integer, for these types there's little difference between using an initialiser list and using assignment, but an initialiser list should still be prefered to be consistent with the times when it does make a difference. Any C++ book should explain initialiser lists.

The second difference is that the books code is using uniform initialisation syntax. You can tell this because it uses {} instead of the usual (). But in the case of an initialiser list I think this makes no difference.

john
  • 85,011
  • 4
  • 57
  • 81