Having question about constructor

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Having question about constructor

thomaschan
Since every constructor should return 'this', does it has a default 'argument 0' which named 'this', just as the method?
 
Plus, when compiling this constructor,

constructor SquareGame new() {
     return this;
}


Can the VM code be like this?
function SquareGame.new 0
push argument 0
pop pointer 0
push pointer 0
return


But when I use the JackCompiler to output this file, it appears to be like this:
function SquareGame.new 0
push constant 0
call Memory.alloc 1
pop pointer 0
push pointer 0
return


I don't understand why it should use Memory.alloc.
Reply | Threaded
Open this post in threaded view
|

Re: Having question about constructor

cadet1620
Administrator
thomaschan wrote
Since every constructor should return 'this', does it has a default 'argument 0' which named 'this', just as the method?
Constructors do not have this as a default argument. The object doesn't exist when the constructor is called so there in no pointer to pass yet. Argument 0 is the first real argument, like a function.
When I use the JackCompiler to output this file, it appears to be like this:
function SquareGame.new 0
push constant 0
call Memory.alloc 1
pop pointer 0
push pointer 0
return
Only the compiler knows how much memory is needed for the object's variables, so it must generate code that calls Memory.alloc() to allocate the memory block required to hold the object. In your test case, the SquareGame object had no "fields" declared, so 0 was passed to Memory.alloc().

The real SquareGame has 2 fields so the constructor will start with "push constant 2".

Effectively, the constructor is doing
    this = Memory.alloc( number of fields );
    // Initialize fields ...
    return this;

--Mark