Next: , Up: Overloading Objects   [Contents][Index]

34.4.1 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

function [y, dy] = polyval (p, varargin)
  if (nargout == 2)
    [y, dy] = polyval (fliplr (p.poly), varargin{:});
    y = polyval (fliplr (p.poly), varargin{:});

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.

function h = plot (p, varargin)
  n = 128;
  rmax = max (abs (roots (p.poly)));
  x = [0 : (n - 1)] / (n - 1) * 2.2 * rmax - 1.1 * rmax;
  if (nargout > 0)
    h = plot (x, p(x), varargin{:});
    plot (x, p(x), varargin{:});

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.

function b = double (a)
  b = a.poly;