RAD Studio (Common)
ContentsIndex
PreviousUpNext
Classes and Objects

This topic covers the following material:

  • Declaration syntax of classes
  • Inheritance and scope
  • Visibility of class members
  • Forward declarations and mutually dependent classes

A class, or class type, defines a structure consisting of fields, methods, and properties. Instances of a class type are called objects. The fields, methods, and properties of a class are called its components or members.

  • A field is essentially a variable that is part of an object. Like the fields of a record, a class' fields represent data items that exist in each instance of the class.
  • A method is a procedure or function associated with a class. Most methods operate on objects, that is, instances of a class. Some methods (called class methods) operate on class types themselves.
  • A property is an interface to data associated with an object (often stored in a field). Properties have access specifiers, which determine how their data is read and modified. From other parts of a program outside of the object itself a property appears in most respects like a field.
Objects are dynamically allocated blocks of memory whose structure is determined by their class type. Each object has a unique copy of every field defined in the class, but all instances of a class share the same methods. Objects are created and destroyed by special methods called constructors and destructors. 

A variable of a class type is actually a pointer that references an object. Hence more than one variable can refer to the same object. Like other pointers, class-type variables can hold the value nil. But you don't have to explicitly dereference a class-type variable to access the object it points to. For example, SomeObject.Size := 100 assigns the value 100 to the Size property of the object referenced by SomeObject; you would not write this as SomeObject^.Size := 100

A class type must be declared and given a name before it can be instantiated. (You cannot define a class type within a variable declaration.) Declare classes only in the outermost scope of a program or unit, not in a procedure or function declaration. 

A class type declaration has the form

type 
   className = class [abstract | sealed] (ancestorClass)
      memberList  
   end;

where className is any valid identifier, the sealed or abstract keyword is optional, (ancestorClass) is optional, and memberList declares members - that is, fields, methods, and properties - of the class. If you omit (ancestorClass), then the new class inherits directly from the predefined TObject class. If you include (ancestorClass) and memberList is empty, you can omit end. A class type declaration can also include a list of interfaces implemented by the class; see Implementing Interfaces

If a class is marked sealed, then it cannot be extended through inheritance. If a class is marked abstract, then it cannot be instantiated directly using the Create constructor. An entire class can be declared abstract even if it does not contain any abstract virtual methods. A class cannot be both abstract and sealed

Methods appear in a class declaration as function or procedure headings, with no body. Defining declarations for each method occur elsewhere in the program. 

For example, here is the declaration of the TMemoryStream class from the Classes unit.

     type TMemoryStream = class(TCustomMemoryStream) 
            private 
              FCapacity: Longint; 
              procedure SetCapacity(NewCapacity: Longint); 
            protected 
              function Realloc(var NewCapacity: Longint): Pointer; virtual; 
              property Capacity: Longint read FCapacity write SetCapacity; 
            public 
              destructor Destroy; override;  
              procedure Clear; 
              procedure LoadFromStream(Stream: TStream); 
              procedure LoadFromFile(const FileName: string); 
              procedure SetSize(NewSize: Longint); override; 
              function Write(const Buffer; Count: Longint): Longint; override; 
          end;

TMemoryStream descends from TCustomMemoryStream (in the Classes unit), inheriting most of its members. But it defines - or redefines - several methods and properties, including its destructor method, Destroy. Its constructor, Create, is inherited without change from TObject, and so is not redeclared. Each member is declared as private, protected, or public (this class has no published members). These terms are explained below. 

Given this declaration, you can create an instance of TMemoryStream as follows:

 var stream: TMemoryStream; 
     stream := TMemoryStream.Create;

When you declare a class, you can specify its immediate ancestor. For example,

type TSomeControl = class(TControl);

declares a class called TSomeControl that descends from TControl. A class type automatically inherits all of the members from its immediate ancestor. Each class can declare new members and can redefine inherited ones, but a class cannot remove members defined in an ancestor. Hence TSomeControl contains all of the members defined in TControl and in each of TControl's ancestors. 

The scope of a member's identifier starts at the point where the member is declared, continues to the end of the class declaration, and extends over all descendants of the class and the blocks of all methods defined in the class and its descendants.

TObject and TClass

The TObject class, declared in the System unit, is the ultimate ancestor of all other classes. TObject defines only a handful of methods, including a basic constructor and destructor. In addition to TObject, the System unit declares the class reference type TClass:

TClass = class of TObject;

If the declaration of a class type doesn't specify an ancestor, the class inherits directly from TObject. Thus

type TMyClass = class
      ... 
     end;

is equivalent to

type TMyClass = class(TObject) 
      ... 
     end;

The latter form is recommended for readability.

Compatibility of Class Types

A class type is assignment-compatible with its ancestors. Hence a variable of a class type can reference an instance of any descendant type. For example, given the declarations

type 
     TFigure = class(TObject); 
     TRectangle = class(TFigure); 
     TSquare = class(TRectangle); 
var 
     Fig: TFigure;

the variable Fig can be assigned values of type TFigure, TRectangle, and TSquare.

Object Types

The Win32 Delphi compiler allows an alternative syntax to class types, which you can declare object types using the syntax

type objectTypeName = object (ancestorObjectType)
        memberList
     end;

where objectTypeName is any valid identifier, (ancestorObjectType) is optional, and memberList declares fields, methods, and properties. If (ancestorObjectType) is omitted, then the new type has no ancestor. Object types cannot have published members. 

Since object types do not descend from TObject, they provide no built-in constructors, destructors, or other methods. You can create instances of an object type using the New procedure and destroy them with the Dispose procedure, or you can simply declare variables of an object type, just as you would with records. 

Object types are supported for backward compatibility only. Their use is not recommended on Win32.

Every member of a class has an attribute called visibility, which is indicated by one of the reserved words private, protected, public, published, or automated. For example,

published property Color: TColor read GetColor write SetColor;

declares a published property called Color. Visibility determines where and how a member can be accessed, with private representing the least accessibility, protected representing an intermediate level of accessibility, and public, published, and automated representing the greatest accessibility. 

If a member's declaration appears without its own visibility specifier, the member has the same visibility as the one that precedes it. Members at the beginning of a class declaration that don't have a specified visibility are by default published, provided the class is compiled in the {$M+} state or is derived from a class compiled in the {$M+} state; otherwise, such members are public

For readability, it is best to organize a class declaration by visibility, placing all the private members together, followed by all the protected members, and so forth. This way each visibility reserved word appears at most once and marks the beginning of a new 'section' of the declaration. So a typical class declaration should like this:

type 
    TMyClass = class(TControl) 
      private 
         ...  { private declarations here } 
      protected 
         ...  { protected declarations here } 
      public 
         ...  { public declarations here } 
      published 
         ...  { published declarations here } 
    end;

You can increase the visibility of a member in a descendant class by redeclaring it, but you cannot decrease its visibility. For example, a protected property can be made public in a descendant, but not private. Moreover, published members cannot become public in a descendant class. For more information, see Property overrides and redeclarations.

Private, Protected, and Public Members

A private member is invisible outside of the unit or program where its class is declared. In other words, a private method cannot be called from another module, and a private field or property cannot be read or written to from another module. By placing related class declarations in the same module, you can give the classes access to one another's private members without making those members more widely accessible. 

A protected member is visible anywhere in the module where its class is declared and from any descendant class, regardless of the module where the descendant class appears. A protected method can be called, and a protected field or property read or written to, from the definition of any method belonging to a class that descends from the one where the protected member is declared. Members that are intended for use only in the implementation of derived classes are usually protected. 

A public member is visible wherever its class can be referenced.

Strict Visibility Specifiers

In addition to private and protected visibility specifiers, the Delphi compiler supports additional visibility settings with greater access constraints. These settings are strict private and strict protected visibility. These settings can be used in Win32 applications. 

Class members with strict private visibility are accessible only within the class in which they are declared. They are not visible to procedures or functions declared within the same unit. Class members with strict protected visibility are visible within the class in which they are declared, and within any descendant class, regardless of where it is declared. Furthermore, when instance members (those declared without the class or class var keywords) are declared strict private or strict protected, they are inaccessible outside of the instance of a class in which they appear. An instance of a class cannot access strict protected or strict protected instance members in other instances of the same class. 

Delphi's traditional private visibility specifier maps to the CLR's assembly visibility. Delphi's protected visibility specifier maps to the CLR's assembly or family visibility.

Note: The word strict is treated as a directive within the context of a class declaration. Within a class declaration you cannot declare a member named 'strict', but it is acceptable for use outside of a class declaration.

Published Members

Published members have the same visibility as public members. The difference is that runtime type information (RTTI) is generated for published members. RTTI allows an application to query the fields and properties of an object dynamically and to locate its methods. RTTI is used to access the values of properties when saving and loading form files, to display properties in the Object Inspector, and to associate specific methods (called event handlers) with specific properties (called events). 

Published properties are restricted to certain data types. Ordinal, string, class, interface, variant, and method-pointer types can be published. So can set types, provided the upper and lower bounds of the base type have ordinal values between 0 and 31. (In other words, the set must fit in a byte, word, or double word.) Any real type except Real48 can be published. Properties of an array type (as distinct from array properties, discussed below) cannot be published. 

Some properties, although publishable, are not fully supported by the streaming system. These include properties of record types, array properties of all publishable types, and properties of enumerated types that include anonymous values. If you publish a property of this kind, the Object Inspector won't display it correctly, nor will the property's value be preserved when objects are streamed to disk. 

All methods are publishable, but a class cannot publish two or more overloaded methods with the same name. Fields can be published only if they are of a class or interface type. 

A class cannot have published members unless it is compiled in the {$M+} state or descends from a class compiled in the {$M+} state. Most classes with published members derive from TPersistent, which is compiled in the {$M+} state, so it is seldom necessary to use the $M directive.

Note: Identifiers that contain Unicode characters are not allowed in published sections of classes, or in types used by published members.

Automated Members (Win32 Only)

Automated members have the same visibility as public members. The difference is that Automation type information (required for Automation servers) is generated for automated members. Automated members typically appear only in Win32 classes . The automated reserved word is maintained for backward compatibility. The TAutoObject class in the ComObj unit does not use automated

The following restrictions apply to methods and properties declared as automated.

  • The types of all properties, array property parameters, method parameters, and function results must be automatable. The automatable types are Byte, Currency, Real, Double, Longint, Integer, Single, Smallint, AnsiString, WideString, TDateTime, Variant, OleVariant, WordBool, and all interface types.
  • Method declarations must use the default register calling convention. They can be virtual, but not dynamic.
  • Property declarations can include access specifiers (read and write) but other specifiers (index, stored, default, and nodefault) are not allowed. Access specifiers must list a method identifier that uses the default register calling convention; field identifiers are not allowed.
  • Property declarations must specify a type. Property overrides are not allowed.
The declaration of an automated method or property can include a dispid directive. Specifying an already used ID in a dispid directive causes an error. 

On the Win32 platform, this directive must be followed by an integer constant that specifies an Automation dispatch ID for the member. Otherwise, the compiler automatically assigns the member a dispatch ID that is one larger than the largest dispatch ID used by any method or property in the class and its ancestors. For more information about Automation (on Win32 only), see Automation objects.

If the declaration of a class type ends with the word class and a semicolon - that is, if it has the form 

type className = class

with no ancestor or class members listed after the word class, then it is a forward declaration. A forward declaration must be resolved by a defining declaration of the same class within the same type declaration section. In other words, between a forward declaration and its defining declaration, nothing can occur except other type declarations. 

Forward declarations allow mutually dependent classes. For example,

type 
      TFigure = class;   // forward declaration 
      TDrawing = class 
         Figure: TFigure; 
           ... 
      end; 
   
      TFigure = class   // defining declaration 
         Drawing: TDrawing; 
           ... 
      end;

Do not confuse forward declarations with complete declarations of types that derive from TObject without declaring any class members.

type 
     TFirstClass = class;   // this is a forward declaration 
     TSecondClass = class   // this is a complete class declaration
     end;                   //
     TThirdClass = class(TObject);  // this is a complete class declaration
Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!