1

I came across the following function definition from a c++ textbook:

Vector& Vector::operator=(const Vector& a) {

  double* p = new double[a.sz]; 
  for (int i=0; i!=a.sz; ++i) 
        p[i] = a.elem[i]; 
  delete[] elem; 
  elem=p;
  sz=a.sz;
  return *this;
}

I have a question about the last statement -- which returns *this instead of this. As far as I remember, this in Java refers to the current object. Am I correct that this in C++ refers to the pointer to the current object? If so, why is it designed in that way? Thanks.

zell
  • 9,830
  • 10
  • 62
  • 115
  • Note that Java doesn't have the notion of pointers or non-primitive values – Caleth Jul 12 '19 at 13:01
  • @Caleth • What Java terminology calls a _reference_, C++ terminology calls a _pointer_. – Eljay Jul 12 '19 at 15:48
  • @Eljay No, C++ has both references and pointers, which are *both* distinct from Java references. E.g. you can rebind a Java reference, you can do arithmetic to; and take the address of; a C++ pointer. – Caleth Jul 12 '19 at 15:49
  • @Caleth • Actually, yes, Java references are C or C++ pointers. The NullPointerException is remnant terminology from before marketing made the decision to alter the terminology (because "pointers are evil"). In C and C++, a pointer can be rebound to a new address. Java does not provide the means to take an address of or perform arithmetics on a Java reference, but that is merely reducing what is allowed on a Java reference (C or C++ pointer). The difference in Java (references) versus C or C++ (pointers) is merely one of each language's particular terminology. – Eljay Jul 12 '19 at 17:41
  • @Eljay A reference is indistinguishable from the object to which it refers. A pointer is a separate object. My point is that C++ has two distinct things, both of which have similarities with aspects of Java's references – Caleth Jul 12 '19 at 22:01
  • @Caleth • My point is that in Java the term "reference" is the same thing in C or C++ as the the term "pointer". – Eljay Jul 13 '19 at 00:09

0 Answers0