Object Oriented Programming
***************************

Octave includes the capability to include user classes, including the features of operator and function overloading.  Equally a user class can be used to encapsulate certain properties of the class so that they cannot be altered accidentally and can be set up to address the issue of class precedence in mixed class operations.

This chapter discussions the means of constructing a user class with the example of a polynomial class, how to query and set the properties of this class, together with the means to overload operators and functions.

Creating a Class
================

We use in the following text a polynomial class to demonstrate the use of object oriented programming within Octave.  This class was chosen as it is simple, and so doesn't distract unnecessarily from the discussion of the programming features of Octave.  However, even still a small understand of the polynomial class itself is necessary to fully grasp the techniques described.

The polynomial class is used to represent polynomials of the form

     a0 + a1 * x + a2 * x^2 + ... + an * x^n

where a0, a1, etc. are real scalars. Thus the polynomial can be represented by a vector

     a = [a0, a1, a2, ..., an];

We therefore now have sufficient information about the requirements of the class constructor for our polynomial class to write it.  All object oriented classes in Octave, must be contained with a directory taking the name of the class, prepended with the @ symbol.  For example, with our polynomial class, we would place the methods defining the class in the @polynomial directory.

The constructor of the class, must have the name of the class itself and so in our example the constructor with have the name @polynomial/polynomial.m.  Also ideally when the constructor is called with no arguments to should return a value object.  So for example our polynomial might look like

     (/polynomial.m)

Note that the return value of the constructor must be the output of the class function called with the first argument being a structure and the second argument being the class name.  An example of the call to this constructor function is then

     p = polynomial ([1, 0, 1]);

Note that methods of a class can be documented.  The help for the constructor itself can be obtained with the constructor name, that is for the polynomial constructor help polynomial will return the help string.  Also the help can be obtained by restricting the search for the help to a particular class, for example help @polynomial/polynomial.  This second method is the only means of getting help for the overloaded methods and functions of the class.

The same is true for other Octave functions that take a function name as an argument.  For example type @polynomial/display will print the code of the display method of the polynomial class to the screen, and dbstop @polynomial/display will set a breakpoint at the first executable line of the display method of the polynomial class.

To check where a variable is a user class, the isobject and isa functions can be used.  For example:

     p = polynomial ([1, 0, 1]);
     isobject (p)
       => 1
     isa (p, "polynomial")
       => 1

(isobject)

The available methods of a class can be displayed with the methods function.

(methods)

To inquire whether a particular method is available to a user class, the ismethod function can be used.

(ismethod)

For example:

     p = polynomial ([1, 0, 1]);
     ismethod (p, "roots")
       => 1

Manipulating Classes
====================

There are a number of basic classes methods that can be defined to allow the contents of the classes to be queried and set.  The most basic of these is the display method.  The display method is used by Octave when displaying a class on the screen, due to an expression that is not terminated with a semicolon.  If this method is not defined, then Octave will printed nothing when displaying the contents of a class.

(display)

An example of a display method for the polynomial class might be

     (/display.m)

Note that in the display method, it makes sense to start the method with the line fprintf ("%s =", inputname (1)) to be consistent with the rest of Octave and print the variable name to be displayed when displaying the class.

To be consistent with the Octave graphic handle classes, a class should also define the get and set methods.  The get method should accept one or two arguments, and given one argument of the appropriate class it should return a structure with all of the properties of the class.  For example:

     (/get.m)

Similarly, the set method should taken as its first argument an object to modify, and then take property/value pairs to be modified.

     (/set.m)

Note that as Octave does not implement pass by reference, than the modified object is the return value of the set method and it must be called like

     p = set (p, "a", [1, 0, 0, 0, 1]);

Also the set method makes use of the subsasgn method of the class, and this method must be defined.  The subsasgn method is discussed in the next section.

Finally, user classes can be considered as a special type of a structure, and so they can be saved to a file in the same manner as a structure.  For example:

     p = polynomial ([1, 0, 1]);
     save userclass.mat p
     clear p
     load userclass.mat

All of the file formats supported by save and load are supported.  In certain circumstances, a user class might either contain a field that it makes no sense to save or a field that needs to be initialized before it is saved.  This can be done with the saveobj method of the class

(saveobj)

saveobj is called just prior to saving the class to a file.  Likely, the loadobj method is called just after a class is loaded from a file, and can be used to ensure that any removed fields are reinserted into the user object.

(loadobj)

Indexing Objects
================

Defining Indexing And Indexed Assignment
----------------------------------------

Objects can be indexed with parentheses, either like A (IDX) or like A {IDX}, or even like A (IDX).FIELD.  However, it is up to the user to decide what this indexing actually means.  In the case of our polynomial class P (N) might mean either the coefficient of the N-th power of the polynomial, or it might be the evaluation of the polynomial at N.  The meaning of this subscripted referencing is determined by the subsref method.

(subsref)

For example we might decide that indexing with "()" evaluates the polynomial and indexing with "{}" returns the N-th coefficient (of N-th power).  In this case the subsref method of our polynomial class might look like

     (/subsref.m)

The equivalent functionality for subscripted assignments uses the subsasgn method.

(subsasgn)

(optimize_subsasgn_calls)

Note that the subsref and subsasgn methods always receive the whole index chain, while they usually handle only the first element.  It is the responsibility of these methods to handle the rest of the chain (if needed), usually by forwarding it again to subsref or subsasgn.

If you wish to use the end keyword in subscripted expressions of an object, then the user needs to define the end method for the class.  For example, the end method for our polynomial class might look like

     (/end.m)

which is a fairly generic end method that has a behavior similar to the end keyword for Octave Array classes.  It can then be used as follows:

     p = polynomial ([1,2,3,4]);
     p(end-1)
       => 3

Objects can also be used as the index in a subscripted expression themselves and this is controlled with the subsindex function.

(subsindex)

Finally, objects can equally be used like ranges, using the colon method

(colon)

Indexed Assignment Optimization
-------------------------------

Octave's ubiquitous lazily-copied pass-by-value semantics implies a problem for performance of user-defined subsasgn methods.  Imagine a call to subsasgn:

       ss = substruct ("()",{1});
       x = subsasgn (x, ss, 1);

and the corresponding method looking like this:

       function x = subsasgn (x, ss, val)
         ...
         x.myfield (ss.subs{1}) = val;
       endfunction

The problem is that on entry to the subsasgn method, x is still referenced from the caller's scope, which means that the method will first need to unshare (copy) x and x.myfield before performing the assignment.  Upon completing the call, unless an error occurs, the result is immediately assigned to x in the caller's scope, so that the previous value of x.myfield is forgotten.  Hence, the Octave language implies a copy of N elements (N being the size of x.myfield), where modifying just a single element would actually suffice, i.e., degrades a constant-time operation to linear-time one. This may be a real problem for user classes that intrinsically store large arrays.

To partially solve the problem, Octave uses a special optimization for user-defined subsasgn methods coded as m-files.  When the method gets called as a result of the built-in assignment syntax (not direct subsasgn call as shown above), i.e.

       x(1) = 1;

AND if the subsasgn method is declared with identical input and output argument, like in the example above, then Octave will ignore the copy of x inside the caller's scope; therefore, any changes made to x during the method execution will directly affect the caller's copy as well. This allows, for instance, defining a polynomial class where modifying a single element takes constant time.

It is important to understand the implications that this optimization brings. Since no extra copy of x in the caller's scope will exist, it is solely the callee's responsibility to not leave x in an invalid state if an error occurs throughout the execution.  Also, if the method partially changes x and then errors out, the changes will affect x in the caller's scope.  Deleting or completely replacing x inside subsasgn will not do anything, however, only indexed assignments matter.

Since this optimization may change the way code works (especially if badly written), a built-in variable optimize_subsasgn_calls is provided to control it.  It is on by default.  Another option to avoid the effect is to declare subsasgn methods with different output and input arguments, like this:

       function y = subsasgn (x, ss, val)
         ...
       endfunction

Overloading Objects
===================

Function Overloading
--------------------

Any Octave function can be overloaded, and allows an object specific version of this function to be called as needed.  A pertinent example for our polynomial class might be to overload the polyval function like

     (/polyval.m)

This function just hands off the work to the normal Octave polyval function.  Another interesting example for an overloaded function for our polynomial class is the plot function.

     (/plot.m)

which allows polynomials to be plotted in the domain near the region of the roots of the polynomial.

Functions that are of particular interest to be overloaded are the class conversion functions such as double.  Overloading these functions allows the cast function to work with the user class and can aid in the use of methods of other classes with the user class.  An example double function for our polynomial class might look like.

     (/double.m)

Operator Overloading
--------------------

The following table shows, for each built-in numerical operation, the corresponding function name to use when providing an overloaded method for a user class.

  Operation   Method   Description
  a + b   plus (a, b)   Binary addition
  a - b   minus (a, b)   Binary subtraction operator
  + a   uplus (a)   Unary addition operator
  - a   uminus (a)   Unary subtraction operator
  a .* b   times (a, b)   Element-wise multiplication operator
  a * b   mtimes (a, b)   Matrix multiplication operator
  a ./ b   rdivide (a, b)   Element-wise right division operator
  a / b   mrdivide (a, b)   Matrix right division operator
  a .\ b   ldivide (a, b)   Element-wise left division operator
  a \ b   mldivide (a, b)   Matrix left division operator
  a .^ b   power (a, b)   Element-wise power operator
  a ^ b   mpower (a, b)   Matrix power operator
  a < b   lt (a, b)   Less than operator
  a <= b   le (a, b)   Less than or equal to operator
  a > b   gt (a, b)   Greater than operator
  a >= b   ge (a, b)   Greater than or equal to operator
  a == b   eq (a, b)   Equal to operator
  a != b   ne (a, b)   Not equal to operator
  a & b   and (a, b)   Logical and operator
  a | b   or (a, b)   Logical or operator
  ! b   not (a)   Logical not operator
  a'   ctranspose (a)   Complex conjugate transpose operator
  a.'   transpose (a)   Transpose operator
  a : b   colon (a, b)   Two element range operator
  a : b : c   colon (a, b, c)   Three element range operator
  [a, b]   horzcat (a, b)   Horizontal concatenation operator
  [a; b]   vertcat (a, b)   Vertical concatenation operator
  a(s_1, ..., s_n)   subsref (a, s)   Subscripted reference
  a(s_1, ..., s_n) = b   subsasgn (a, s, b)   Subscripted assignment
  b (a)   subsindex (a)   Convert to zero-based index
   display   display (a)   Commandline display function

Table: Available overloaded operators and their corresponding class method

An example mtimes method for our polynomial class might look like

     (/mtimes.m)

Precedence of Objects
---------------------

Many functions and operators take two or more arguments and so the case can easily arise that these functions are called with objects of different classes.  It is therefore necessary to determine the precedence of which method of which class to call when there are mixed objects given to a function or operator.  To do this the superiorto and inferiorto functions can be used

(superiorto)

(inferiorto)

For example with our polynomial class consider the case

     2 * polynomial ([1, 0, 1]);

That mixes an object of the class "double" with an object of the class "polynomial".  In this case we like to ensure that the return type of the above is of the type "polynomial" and so we use the superiorto function in the class constructor.  In particular our polynomial class constructor would be modified to be

     (/polynomial_superiorto.m)

Note that user classes always have higher precedence than built-in Octave types.  So in fact marking our polynomial class higher than the "double" class is in fact not necessary.

When faced with two objects that have the same precedence, Octave will use the method of the object that appears first on the list of arguments.

Inheritance and Aggregation
===========================

Using classes to build new classes is supported by octave through the use of both inheritance and aggregation.

Class inheritance is provided by octave using the class function in the class constructor.  As in the case of the polynomial class, the octave programmer will create a struct that contains the data fields required by the class, and then call the class function to indicate that an object is to be created from the struct.  Creating a child of an existing object is done by creating an object of the parent class and providing that object as the third argument of the class function.

This is easily demonstrated by example.  Suppose the programmer needs an FIR filter, i.e., a filter with a numerator polynomial but a unity denominator polynomial.  In traditional octave programming, this would be performed as follows.

     octave:1> x = [some data vector];
     octave:2> n = [some coefficient vector];
     octave:3> y = filter (n, 1, x);

The equivalent class could be implemented in a class directory @FIRfilter that is on the octave path.  The constructor is a file FIRfilter.m in the class directory.

     (/FIRfilter.m)

As before, the leading comments provide command-line documentation for the class constructor.  This constructor is very similar to the polynomial class constructor, except that we pass a polynomial object as the third argument to the class function, telling octave that the FIRfilter class will be derived from the polynomial class.  Our FIR filter does not have any data fields, but we must provide a struct to the class function.  The class function will add an element named polynomial to the object struct, so we simply add a dummy element named polynomial as the first line of the constructor. This dummy element will be overwritten by the class function.

Note further that all our examples provide for the case in which no arguments are supplied.  This is important since octave will call the constructor with no arguments when loading objects from save files to determine the inheritance structure.

A class may be a child of more than one class (see the documentation for the class function), and inheritance may be nested.  There is no limitation to the number of parents or the level of nesting other than memory or other physical issues.

As before, we need a display method.  A simple example might be

     (/display.m)

Note that we have used the polynomial field of the struct to display the filter coefficients.

Once we have the class constructor and display method, we may create an object by calling the class constructor.  We may also check the class type and examine the underlying structure.

     octave:1> f = FIRfilter (polynomial ([1 1 1]/3))
     f.polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
     octave:2> class (f)
     ans = FIRfilter
     octave:3> isa (f,"FIRfilter")
     ans =  1
     octave:4> isa (f,"polynomial")
     ans =  1
     octave:5> struct (f)
     ans =
     {
     polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
     }

We only need to define a method to actually process data with our filter and our class is usable.  It is also useful to provide a means of changing the data stored in the class.  Since the fields in the underlying struct are private by default, we could provide a mechanism to access the fields.  The subsref method may be used for both.

     (/subsref.m)

The "()" case allows us to filter data using the polynomial provided to the constructor.

     octave:2> f = FIRfilter (polynomial ([1 1 1]/3));
     octave:3> x = ones (5,1);
     octave:4> y = f(x)
     y =

        0.33333
        0.66667
        1.00000
        1.00000
        1.00000

The "." case allows us to view the contents of the polynomial field.

     octave:1> f = FIRfilter (polynomial ([1 1 1]/3));
     octave:2> f.polynomial
     ans = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2

In order to change the contents of the object, we need to define a subsasgn method.  For example, we may make the polynomial field publicly writable.

     (/subsasgn.m)

So that

     octave:6> f = FIRfilter ();
     octave:7> f.polynomial = polynomial ([1 2 3]);
     f.polynomial = 1 + 2 * X + 3 * X ^ 2

Defining the FIRfilter class as a child of the polynomial class implies that and FIRfilter object may be used any place that a polynomial may be used.  This is not a normal use of a filter, so that aggregation may be a more sensible design approach.  In this case, the polynomial is simply a field in the class structure.  A class constructor for this case might be

     (/FIRfilter_aggregation.m)

For our example, the remaining class methods remain unchanged.