next up previous contents
Next: Object Templates and Inheritance Up: C++ for Ocean Modeling Previous: Objects Introduction

Objects: Operators, and Overloading

In constructing our object, we can declare how some special operators - including +, -, = work for our object. If the object is primarily a mathematical one (as most of ours tend to be) these operations are a good idea. This also lets us use standard math in writing operations in cases where we might not be able to in Fortran. For instance, in one part of my SSMI processing, I add the brightness temperatures for later averaging. At the moment, I do this in C with abstract data type syntax, like sum.t19v = sum.t19v + new.t19v; where I then repeat this for each data entry. In C++, I'd write it as sum = sum + new; and avoid the extra opportunity for typos.

In between all of this is the fact that since we declare operations (and functions) with respect to a specific class, we have the opportunity to use the same function name in different contexts. For instance, having defined a version of + to work on SSMI points, we can write x + y where x and y are ssmi points, or where they're integers. We make the compiler figure out which one is appropriate in the context. This is called overloading. Because of overloading, we are able to focus more on what we're trying to do than on the details of what the computer knows about.

Overloading also permits y = x.locate(ij); and z = x.locate(ll); to be interpreted correctly. In the first case, I'm requesting the latitude-longitude location of a given i,j point in a grid. In the second, I'm requesting the i,j location of a given latitude-longitude point in the grid. In both cases, we want a location so we use the same name. What sort of location we want is determined by the type of information we pass the function. The compiler sorts out which locate function to use, rather than making us look up (and remember) two different names.

It goes beyond this, even. Since x is some type of object (maybe a polar stereographic grid, maybe a mercator grid), not only does the compiler pull out whether I want the locate that gives a latitude-longitude versus an i,j, it also determines what grid system's conversion I'm going to need. Since we have a number of different map projections, and a number of specializations of each projection, there would be something like 500 function names to remember in a Fortran code, as compared to the one that we have via C++. One alternate method, used in the w3ft32 routine, is instead of having dozens of subroutines, to pass the grid numbers that correspond to the grids you want. The code is well-written, but instead of memorizing dozens of subroutine names, you have to memorize dozens of grid code numbers. Overloading avoids both.


next up previous contents
Next: Object Templates and Inheritance Up: C++ for Ocean Modeling Previous: Objects Introduction
Robert Grumbine
2000-06-14