3-D Point Using Inheritance
/* * Extend the point class to three dimensions */ #ifndef _point3d_h_ #define _point3d_h_ #include <string> #include "point.h" class Point3d: public Point { public: // Construct a 3-d point. The notation at the end of the first // line calls the base class constructor. Point3d(double x = 0.0, double y = 0.0, double z = 0.0): Point(x,y), m_z(z) { } // The third coordinate. First two are inherited. double applicate() const { return m_z; } // To-string. Just start over rather than having to call the // base and insert in front of the closin paren. string tos() const { return "(" + to_string(abscissa()) + "," + to_string(ordinate()) + "," + to_string(m_z) + ")"; } // This a conversion utility which is useful for some of our // implementation, and might as well be public in case it's useful // to the client. Takes a 2-d point and a z coordinate, and adds the // the z to build a 3-d point. Point3d from2d(const Point &p, double z = 0.0) const { return Point3d(p.abscissa(), p.ordinate(), z); } // Add or subtract two points. Notice the use of Point3d plus(const Point3d &b) const { return from2d(Point::plus(b), m_z + b.m_z); } Point3d minus(const Point3d &b) const { return from2d(Point::minus(b), m_z - b.m_z); } // Negate the point Point3d negate() const { return from2d(Point::negate(), -m_z); } // Move the point by a given amount void move(double dx, double dy, double dz) { Point::move(dx, dy); m_z += dz; } // I could do this in terms of the base class distance, but it // means computing an extra square root. double distance(const Point3d &b) const { double xd = abscissa() - b.abscissa(); double yd = ordinate() - b.ordinate(); double zd = m_z - b.m_z; return sqrt(xd*xd + yd*yd + zd*zd); } // The base class is called area, which doesn't make sense anymore. // Needs to be volume. So we get rid of the inherited area, and // create a volume() method instead. double area(const Point &b) const = delete; double volume(const Point3d &b) const { return Point::area(b) * abs(m_z - b.m_z); } private: // The third dimension. double m_z; }; #endif

This defines a class Point3d which extends Point. Things to note:

Super is one of those ideas I wish C++ would please steal from Java. But it has not done so.