Difference between revisions of "Object"

From Free Pascal wiki
Jump to navigationJump to search
(See Also Programming Using Objects)
Line 77: Line 77:
 
current errors:2<br/>
 
current errors:2<br/>
 
Destructor not needed - nothing allocated on the heap
 
Destructor not needed - nothing allocated on the heap
 +
 +
== See Also ==
 +
[[Programming Using Objects]]
  
 
[[Category:Data types]]
 
[[Category:Data types]]

Revision as of 11:48, 28 July 2016

Deutsch (de) English (en) français (fr)

The reserved word object is used to construct complex data types that contain both functions, procedures and data. Object allows the user to perform Object-Oriented Programming (OOP). It is similar to class in the types it can create, but by default objects are created on the stack, while class data is created on the heap. However, object created types can be created on the heap by using the new procedure. Object was introduced in Turbo Pascal, while class was introduced in Delphi. Object is maintained for backward compatibility with Turbo Pascal and has largely been superseded by class.

Example skeleton of the creation of the data type object:

type
  TTest = object
  private
    { private declarations }
  public
    { public declarations }
  end;

Example skeleton of the create of a packed version of the data type object:

type
  TTest = packed object
  private
    { private declarations }
  public
    { public declarations }
  end;

Example with constructor and destructor:

type
   TTest = object
   private 
     {private declarations}
     total_errors : Integer;
   public
     {public declarations}
     constructor Init;
     destructor Done;
     procedure IncrementErrors;
     function GetTotalErrors : Integer;
   end;

procedure TTest.IncrementErrors;
begin
  Inc(total_errors);
end;
    
function TTest.GetTotalErrors : Integer;
begin
   GetTotalErrors := total_errors;
end;

constructor TTest.Init;
begin
  total_errors := 0;
end;

destructor TTest.Done;
begin
   WriteLn('Destructor not needed - nothing allocated on the heap');
end;

var
   error_counter: TTest;

begin
   error_counter.Init; // unlike C++, constructors must be explicitly called
   error_counter.IncrementErrors;
   error_counter.IncrementErrors;
   WriteLn('current errors:', error_counter.GetTotalErrors);
   error_counter.Done
end.

Output:
current errors:2
Destructor not needed - nothing allocated on the heap

See Also

Programming Using Objects