Refection return in C++

Asked

Viewed 340 times

2

I cannot understand what the following function returns.

int * begin(){ //
  return &this->data[0];
}

Does this function return the address of a reference? I didn’t understand it very well.

  • Give more context to the code. What is the type of this->data?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

4

It returns a pointer, which is an address of some object. The operator & takes an address of the object instead of taking the object itself.

In this case returns the address of this, who has a great chance of being a pointer or reference. I wonder if the intention was not to return his own this.

There must be some confusion because the statement & indicates that something is a reference, but depending on the context the same symbol is the operator is something quite different, despite having a relationship.

Understand What is the difference between pointer and reference?.

2

Maybe there are other possibilities. But one of them is a pointer to the first element of the array data of the object of a class implementing the member function begin().

  • this refers to the pointer to the object whose function is called.
  • the operators -> and [] precede the operator &, then we go to them.
    • The associativity of these two operators is left to right.
    • In that case this->data is a pointer to the array data.
    • And this->data[0] is an integer. The first element of the array data.
  • finally the operator & returns the address of the integer this->data[0].

Note that in this case, this->data and &this->data[0] return the same value.

A possible implementation:

#include <iostream>

struct s {
  s() : data{1, 2, 3} {};
  int *begin() { return &this->data[0]; };
  int data[3];
};

int main() {
  s var;
  std::cout << *var.begin() << "\n";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.