Next: , Previous: , Up: Top   [Index]


Methods

Methods

The following sections outline some of the programming features that Ctalk methods implement. The Ctalk Tutorial provides step-by-step instructions on how to write some common method types.

Declaring a method is similar to declaring a C function, but the declaration syntax adds some additional features.

To declare an instance method, use the instanceMethod keyword, as in the following example.

String instanceMethod = set_value (char *s) {

 ... method statements

}

This example declares an instance method, =, which is recognized by objects that belong to the class String and its subclasses. The = in the declaration overloads C’s = operator, so that, instead of assigning a value to a C variable, the method sets the value of its receiver.

In this example, the receiver is an instance of class String.

newObject = "Hello, World!";

If the variable reference immediately preceding = refers to a C variable, then = behaves as the C operator, =.

Ctalk can use most C operators as methods, with the exception of parentheses and prefix operators. Receivers always precede the method message.

For example, the Integer methods invert and bitComp perform the same operations as the C prefix operators ! and ~.

int i;              /* C variable. */
Integer new myInt;  /* Ctalk object. */

i = 0;
myInt = 0;

/* These two statements are equivalent. */
printf ("%d", !i); 
printf ("%d", myInt invert).

/* And so are these two statements. */
printf ("%d", ~i);
printf ("%d", myInt bitComp);

Declaring Methods

The declaration syntax for instance methods is:

classname instanceMethod [alias] funcname (args) { method body }

and for class methods:

classname classMethod [alias] funcname (args) { method body }

If alias is omitted, Ctalk refers to the method by funcname.

In the example at the beginning of this section, if = were omitted, a program could refer to the method by the message, set_value.

With the exception of the primitive methods class, new, classMethod, and instanceMethod, Ctalk declares methods in its class library, or in the program input. See Classes.

Method Parameters

You can use Ctalk class objects to declare method parameters, but you can also declare parameters using C data types, in order to prevent class libraries from being loaded recursively. This is necessary in many of the basic classes.

Regardless of how you declare method parameters, when the method’s message is sent to an object, Ctalk translates C language arguments into class objects.

For example, these two declarations are equivalent.

Integer instanceMethod + add (int i) {
...
}

Integer instanceMethod + add (Integer i) {
...
}

Ctalk does not use objects in C function arguments, so if you need to use objects as parameters, you must write a method instead of a C function.


Next: , Previous: , Up: Top   [Index]