SubclassesTopReference parametersClasses

Classes

Classes are defined similarly to Java, but there are some important differences in the way they are used. See Point. [We'll ignore the #ifndef, #define, and #endif for now, but come back to it later.]

Notice that only the declarations are in the ".h" file while the ".cpp" file has the definitions - all prefixed with Point:: before the method name.

The constructor uses initializers to set the instance variables. If there were more things to do, they would go in the curly brackets. Using the initializers sets the instance variables directly to those values when the space is allocated. If it is initialized in the "{ }" then it will be initialized first to the default value and then reset to the value assigned in the constructor. Thus using initializers is more efficient and less likely to allocate space in the heap that cannot be reclaimed.

There are two types of methods, accessors and mutators. Accessors don't change the instance variables and are marked with const. That makes them usable in situations where parameters are marked const (i.e., can't be changed). That is, one can write a method like

    void m(const &Point pt) {
       ... pt.getX() ... }

Notice that when a parameter is marked const, the only methods that can be sent to it are those marked const. Writing pt.translate(ax,ay) would be illegal. Of course, one is also not allowed to assign to a const parameter. So, the idea is that call by constant reference is used to obtain the same effect as call-by-value (where changes to the formal parameter have no impact on the actual parameter) but does it more efficiently than call-by-value because no copy of the actual parameter is made.

Using const declarations also allows the compiler to more aggressively optimize code. C++ needs more help than Java on this because there are so many strange things programmers can do that seemingly straightforward optimizations can give different results than the original.

Bottom line: Programmers must be aware of all of the consequences of their code and think more about efficiency than with Java.

Nevertheless, work on correct code first and only worry about efficiency later.

In the main function we can see two different ways of using Point: as a variable allocated on the stack and as a pointer (and hence allocated on the heap). The second version is the one that coincides with Java. If you are truly doing object-oriented programming, then you should always allocate objects with new (and hence put them in the heap).

The disadvantage of this is that you must explicitly allocate and deallocate space for the object. The advantage is that subtyping works.


SubclassesTopReference parametersClasses