A Very Simple Inline Class in C++

Tutorial Difficulty Level    

This is the first example of a C++ class definition we have shown you. This not-too-exciting program shows some differences between C++ and Java classes.

To note:

  • The class is declared in the same program as main and couple other functions. In C++, classes aren’t required to be in a file by themselves, or a file with any particular name. It just needs to be defined before it is used, like anything else. Smaller classes are often placed in code with other things.
  • The class definitnion is followed by a the semicolon.
  • The public and private controls mean the same as in Java, but the syntax differs. The keywords are followed by a colon, and introduce sections. The classification applies until changed, and may be changed (or changed back) at any time.
  • The constructor uses a default parameter. These are allowed in any function or method, but are often particularly convenient in constructors.
  • The const after the parameter list declares that the method will not change any object variables. That is, a call to x.f() will not change x.
  • There are two top-level functions, munge and set, which are sent an object as a parameter. When sent without marks, objects are passed by value like other parameters. Objects are often passed by reference (with &).
  • Note that the variables declared as type Point actually contain the objects, not references. Likewise, assignment copies objects; it does not just copy a reference as in Java.