return *this;

edited January 2016 in Questions about Code

Using Processing 2.2.1

  class TTurtle {
    float   flDeg;
    TPoint  P;
    ...
  
  TTurtle& CT (void) {
    P.x = width / 2;
    P.y = height / 2;
    
    flDeg = 0.0;
    return *this;
    }
  }

Line 6 - unexpected Token: TTurtle!

The idea about returning "this" is to use function calls separated with .

  TTurtle T = new TTurtel...
  
  T.CT().LT(45).FW(100);

instead of:

  T.CT();
  T.LT(45);
  T.FW(100);

Why doesn't it work in java?

Tagged:

Answers

  • edited January 2016 Answer ✓
    • When the Java language was created, it was determined it wouldn't have any operators to directly manipulate pointers.
    • So those * and & operators don't act as pointer manipulators in Java.
    • Mostly we'd only find such operators in old languages like C, C++, etc.
    • For modern programming languages, it's just assumed that everything (or almost) is an object already.
    • Therefore all variables (or almost) store the 1st memory address value of 1 object.
    • That initial memory address is called reference rather than pointer.
    • And an object is some contiguous allocated memory block. Generally in the heap region.
    • Thus there's no need for such operators. Variables themselves are "pointers" already!

    TTurtle CT() {
      P.x = .5 * width;
      P.y = .5 * height;
      flDeg = 0.0;
      return this;
    }
    

    Take a look @ my Colour class in the link below:
    https://forum.Processing.org/two/discussion/10362/help-with-a-multidimensional-array

    Most of its methods return this. That is, most of them allow chaining calling. :ar!

    P.S.: Most folks would prefer to type in methods in all lowercase letters:
    Rather than T.CT().LT(45).FW(100);, this 1: t.ct().lt(45).fw(100);. 8->

Sign In or Register to comment.