------------------------------------------------------------------------------
MC logo
Point Class Header File II
[^] Code Examples
------------------------------------------------------------------------------
<<Point Class User File point4.h Point Class Implementation File II>>
#include <iostream>
#include <math.h>

using namespace std;

// Class to represent points.
class Point {
private:
        double xval, yval;
public:
        // Constructor uses default arguments to allow calling with zero, one,
        // or two values.
        Point(double x = 0.0, double y = 0.0) {
                xval = x;
                yval = y;
        }

        // Extractors.
        double x() { return xval; }
        double y() { return yval; }

        // Distance to another point.  Pythagorean thm.
        double dist(Point other);

        // Add or subtract two points.
        Point add(Point b)
        {
                return Point(xval + b.xval, yval + b.yval);
        }
        Point sub(Point b)
        {
                return Point(xval - b.xval, yval - b.yval);
        }

        // Move the existing point.
        void move(double a, double b)
        {
                xval += a;
                yval += b;
        }

        // Print the point on the stream.  The class ostream is a base class
        // for output streams of various types.
        void print(ostream &strm)
        {
                strm << "(" << xval << "," << yval << ")";
        }
};

This is exactly like the previous point header file, except the body of one function is omitted. The body in the implementation file, as you will see when you press the button. The notation looks somewhat like an abstract function in Java, but it's not that at all. Think of it as a prototype of a method.

The usual practice in C++ is to include short-bodied functions in the header with the class, and place longer functions in an implementation file. This is important when several files are including the header, since the time to compile the header is spent whenever it is included. If the iostream header included all its bodies, compiling a C++ file would take even longer. As it is, those bodies are compiled only once.
<<Point Class User File Point Class Implementation File II>>