Point Class Defined in a Header
File: point.h
#include <iostream> #include <string> #include <cmath> using namespace std; #ifndef _point_h_ #define _point_h_ /* * Class to represent a single point. */ class Point { public: // Construct a point with the indicated coordinates. Point(double x = 0.0, double y = 0.0) { m_x = x; m_y = y; } // Return either ordinate. double abscissa() const { return m_x; } double ordinate() const { return m_y; } // Produce a string for printing. string tos() const { return "(" + to_string(m_x) + "," + to_string(m_y) + ")"; } // Add or subtract two points Point plus(const Point &b) const { return Point(m_x + b.m_x, m_y + b.m_y); } Point minus(const Point &b) const { return Point(m_x - b.m_x, m_y - b.m_y); } // Negate the point Point negate() const { return Point(-m_x, -m_y); } // Move the point by a given amount void move(double dx, double dy) { m_x += dx; m_y += dy; } // Return the distance between points double distance(const Point &b) const { double xd = m_x - b.m_x; double yd = m_y - b.m_y; return sqrt(xd*xd + yd*yd); } // Return the area of the rectangle whose corners are the // current point and the argument. double area(const Point &b) const { return abs(m_x - b.m_x) * abs(m_y - b.m_y); } private: // The coordinates of the point. double m_x, m_y; }; #endif

This is a class created in a file by itself. The file type is .h by convention, though this is not a rule of the language. It is usual to name the file after the class, but there is no requirement about that, either.

There is an odd notation near the top:

#ifndef _point_h_ #define _point_h_
and at the bottom
This is a compile-time if statement, obeyed by the compiler during translation (rather thah having the compiler translate it to be obeyed at run time). The first tests of the symbol _point_h_ is undefined. If it is undefined, then compiler defines it, then reads the rest of the file. If it is defined, the compiler skips to the matching #endif, which effectively skips the whole file. The purpose of all this is to prevent the class defintion from being read more than once. This can become a problem in complex, multi-file programs. For now, just follow the pattern when you create the class. Choose a symbol which looks like the file name.