Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a class array element with . in C++ or mistake in Stroustrup book

Tags:

c++

In the book Programming Principles and Practice with C++ by B. Stroustrup I have come across a piece of code where the argument is the array of a basic version of the vector class. The class is defined as

class vector {
    int sz;
    double * elem;
public:
    vector(const vector &);
    //...
};
//...
vector::vector(const vector &arg)
     :sz{arg.sz},elem{new double[arg.sz]}
{
     copy(arg.elem,arg.elem.sz,elem);
}

My questions: is 'arg.elem.sz' a valid expression? If yes, What is this accessing?

(By the way, I have tried to write a simple piece of code to try this, but I get an error. As arg.elem is a pointer, it expects me to do something more like 'arg.elem->')

Thanks!

EDIT/UPDATE: the syntax seems to be correct. Looking at the definition of copy, the argument is an 'iterator'. I suspect there must be something about converting the argument to an iterator type, then getting the sz-th pointed element becomes accessing the element of the iterator? Clarifications welcomed :)

like image 432
Silvia Avatar asked Apr 17 '17 12:04

Silvia


1 Answers

This is just a typo, the arg.elem.sz is not a valid expression because the arg.elem is a double* which has no member to access (nor with the -> opertor). It should be arg.elem + arg.sz there because this is how the std::copy works.

In your update you asked about the iterator and the std::copy algorithm. The std::copy is a function template which accepts any type as input and as output iterators if they satisfy the requirements of an input iterator and of an output iterator. A pointer to an array element satisfies the mentioned requirements, so the arg.elem as being an double* can be used as an iterator.

If we change the questioned line of code to the following, it will make sense:

copy(arg.elem, arg.elem + arg.sz, elem);

The code above will copy the content of array between arg.elem and arg.elem + arg.sz to the array pointed by elem.

like image 61
Akira Avatar answered Nov 09 '22 00:11

Akira