-2

I have an simple beginner questions. Here is the code block:

  SimpleString& operator=(const SimpleString& other) {
    if(this == &other)
      return *this;
    const auto new_buffer = new char[other.max_size];
    delete[] buffer;
    buffer = new_buffer;
    length = other.length;
    max_size = other.max_size;
    std::strncpy(buffer, other.buffer, max_size);
    return *this;
  }

Here ist the full code: https://pastebin.com/2qYxq10q

I dont understand, why this is a pointer in the second line and *this in the third line should also be pointer, because the return type of the method has to be a pointer. In my perception in the third line should also stand this and not *this.

Has anybody at least a link with the explanation.

john
  • 85,011
  • 4
  • 57
  • 81
Tom Henn
  • 125
  • 6
  • 1
    The return type is a reference, not a pointer. – tkausl Apr 29 '20 at 09:49
  • 1
    @tkausl see https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in A reference is a pointer but is a constant pointer. – barlop Apr 29 '20 at 09:51
  • 1
    @barlop thats an implementation detail. – tkausl Apr 29 '20 at 09:52
  • @tkausl well it's an implementation detail that conflicts with, (shows to be wrong?) the idea that a reference is not a pointer. From what I can tell, a pointer is an address, as is a reference. The issue is whether one is talking of an address stored in a memory location, or an address of a memory location (where you're not fetching the address from a memory location). – barlop Apr 29 '20 at 09:54
  • 4
    @barlop That's a very mixed up explanation. References are not pointers, you're thinking about how they might be implemented, but from the language point of view they are different entities. – john Apr 29 '20 at 10:06
  • @john I see what u mean.. e.g. "pass by reference" is passing a reference.. in the C++ sense of the term.. I think java might use the term reference differently. In java a value that is a pointer to an object, might be called a reference or object ref and in java u can't do &var or even *var. So in C++ terminology a ref is an address that merely marks a location and is not a value in a location. Given that pass by ref goes by C++ terminology, I wonder if maybe the C++ terminological distinction between reference and pointer,is the standard/conventional/traditional one in Comp Sci. – barlop Apr 29 '20 at 12:46

1 Answers1

3

The return type of the method is a reference not a pointer. In SimpleString& the & means reference, a pointer would be SimpleString*.

john
  • 85,011
  • 4
  • 57
  • 81
  • I have understand, that there is a difference between pointers and references. But that is not my core question. The method expects to return a reference but returns a pointer? – Tom Henn Apr 29 '20 at 10:11
  • If `p` is a pointer to something, then the expression `*p` is a reference to the same thing. – john Apr 29 '20 at 10:16