简体   繁体   中英

What happens when we create a parameterized constructor with a pointer arguement?

For example, can you explain what would happen in the following code?

class Vector{
  int v[3];
  Vector(int *x);//parameterized constructor created
};

Vector::Vector(int *x)//definition of the parameterized constructor
{
  for (int i=0;i<size;i++)
    v[i]=x[i];//what happens here?? why did we take pointer as arguement?
}

From my understanding, by putting v[i]=x[i] we created a new array in which all elements of v are now in x . Why did this require a pointer argument? Couldn't it have been done with a reference & ?

This goes back to older style C habits, when you can use a pointer as an array, by "indexing" it's elements.

Taken from: https://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays

  • A variable declared as an array of some type acts as a pointer to that type. When used by itself, it points to the first element of the array.
  • A pointer can be indexed like an array name.

However, a few notes:

v[i]=x[i] we created a new array

No, you did not create a new array here, the array was already created when the body of the constructor got executed. What happens here is that TO the value v[i] we will assign the value of: *(x + i) ie. the i th. element from the address x points to. Unless you know how x was created and initialized this is pretty dangerous code. Just imagine you can call this method with the address of a single int . I suppose, size is 3 or less, otherwise this code has serious security issues.

You always should check for null pointers, before trying to access the value they point to.

You can pass in the array by reference if you know the size of x at compile time:

Vector(int (&x)[3]);

If you don't know the size at compile time then what you're doing goes from being unsafe code, to blatantly wrong code.

Another option is to use std::array if you know the size at compile time, and std::vector if you don't.

Just to add a bit to previous answers, the indexing operator [] actually dereferences a pointer and shifts it by index*sizeof(type) at the same time. The same relates to declaration of an array. Say, if you declare int a[1]; this means that a is now a pointer to int, ie int* . So if you wanted to pass it to a function as an argument, you would need to specify its type as int* .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM