C++ Tutorial: Inheritance and Composition

July 14th, 2014

In this tutorial, we will look at an important aspect of object-oriented programming: inheritance. Topics we will cover include composition, friend functions, inheritance hierarchies, and access levels. To download the complete C++ project files for this tutorial, click on the GitHub link here. Alternatively, you can copy and paste the code you need further down this post. At the bottom of the post is a list of helpful resources for further information on the topics discussed in this lesson.

This tutorial is a followup from the previous tutorial, C++ Tutorial: Objects and Classes. If you aren’t familiar with objects and classes, you may want to see the introductory tutorial first. Otherwise, please proceed with this tutorial on inheritance.

What is Inheritance?

Inheritance is the process of passing the attributes and behaviors of one class down to descendant classes. For example, you can start with a class named Reptile and have its descendants, Snake and Alligator, inherit the data and members of the Reptile class. Although the Snake and Alligator classes have their own particular attributes and behaviors, each class is derived from the same Reptile class.

is_has (5)

What is Composition

Composition is the process of making one class a data member of another class. For example, you could have a class called Band. The data members of Band could consist of objects from the Guitarist, Drummer, and Vocalist classes. These objects are data members of the Band class, but not descendants or parent classes. They are related by composition, not by inheritance.

is_has (4)

What is a Friend Function?

Sometimes, a friend functions are included in the method declarations of a class. The friend function is not a true member of the class. Instead, it is the signature of a function that is external to the class. The keyword, friend, lets this function have access to the private data members of the class.

friend

Friend functions are commonly used for overriding the iostream operators so that you can print the contents of an object using the double angle brackets rather than a local print method.

friend (7)

Is A vs. Has A Relationships

Inherited classes are commonly described as having an “is ­a” relationship with each other while composition involves a “has­ a” relationship between classes. We can say that Snake is a Reptile and that Alligator is a Reptile. But we cannot say that Guitarist is a Band. Instead, we say that Band has a Guitarist.

Access Specifier: Protected

In the previous tutorial, we looked at the three kinds of access specifiers in C++: private, public, and protected. Remember that private class members are only accessible to the class that contains these members. Public members are accessible from outside the class. Protected members are less restrictive than private ones. Unlike private members, protected members are accessible by derived classes.

access

Note that the direction of inheritance is hierarchal and one-directional. Derived classes have access to all the protected members of a parent class, but parent classes don’t have access to the members of their child classes.

Example Inheritance Hierarchy

Let’s create an example inheritance hierarchy. We will start with the base class, Quadrilateral. Let this class be the template from which we build four­-sided polygon objects. To demonstrate inheritance, let’s give the Quadrilateral class a derived class called Rectangle.

Rectangle objects have all the attributes of Quadrilateral with one additional property. Rectangles not only have four sides, the interior angles must each be ninety-­degrees.

Let’s make another child class at the same level as Rectangle. We’ll call this class Trapezoid. Like Rectangle, Trapezoid has all of the attributes and behaviors of Quadrilateral plus the trait of having at least one pair of parallel opposite sides.

For fun, let’s create a class called Square. Square inherits all the attributes of Rectangle and gains the requirement of having all four sides be the same length.

quad (1)

In the coding implementation below, we will include the Point class via composition in the Quadrilateral class. Basically, the data members of a Quadrilateral consist of four Point objects to represent points on a two-dimensional plane. In the following programming example, we assume that we are working with cyclic quadrilaterals, or quadrilaterals whose vertices line up along the edges of a circle. We will use Ptolemys Theorem to verify that the quadrilateral fits this definition. We will also use Herons Formula to compute the area of a generic quadrilateral.

Its Coding Time!

Either copy and paste the code below into your own C++ project or else download the project files from the GitHub link here. For more information on the topics discussed in this tutorial, please visit the links in the References section at the end of this post.

Point.h

This file declares the attributes and behaviors of the Point class.

//*************************************************************
//  Point.h
//  Inheritance
//
//  Created by Karlina Beringer on July 8, 2014.
//
//  This header file contains the Point class declaration.
//  Point is included in Quadrilateral through composition.
//*************************************************************

#ifndef Point_h
#define Point_h

#include <iostream>
#include <cmath>
#include <string>
using namespace std;

//------------------------------------------------------------------
// Point represents a coordinate pair on a two-dimensional plane.
//------------------------------------------------------------------
class Point
{
private:
    
    // X and Y coordinates describe a point on a plane.
    double X_coordinate, Y_coordinate;
    
public:
    
    // Default constructor creates a Point at the graph origin.
    Point();
    
    // Normal constructor creates a custom Point object.
    Point( double X, double Y );
    
    // Copy constructor creates a clone of a Point object.
    Point( Point & point );
    
    // Setter changes the value of the X_coordinate.
    void setX( double X );
    
    // Setter changes the value of the Y_coordinate.
    void setY( double Y );
    
    // Getter returns the value of the X_coordinate.
    double getX();
    
    // Getter returns the value of the Y_coordinate.
    double getY();
    
    // Getter computes the distance between this and another Point.
    // Distance = Square_Root[ ((X2 - X1)^2) + ((X2 - X1)^2) ]
    double getDistance( Point & point );
    
    // Getter computes the slope between this and another Point.
    // Slope = (Y2 - Y1) / (X2 - X1)
    double getSlope( Point & point );
    
    // Getter prints the coordinate pair of Point in the form ( X, Y ).
    // If no ostream parameter is supplied, default will be cout.
    void print( ostream & output = cout );
    
    // Friend function behaves like Points's print method.
    // Overloads the ostream operator.
    // Friend is NOT a member of Point, but has access to its members.
    friend ostream & operator << ( ostream & output, Point & point );
};

#endif

//*************************************************************
// End of File
//*************************************************************

Point.cpp

This file contains the method definitions of the Point class.

//*************************************************************
//  Point.cpp
//  Inheritance
//
//  Created by Karlina Beringer on July 8, 2014.
//
//  This source file contains the Point class definition.
//  Point is included in Quadrilateral through composition.
//*************************************************************

#include "Point.h"

// Default constructor creates a Point at the graph origin.
Point::Point()
{
    X_coordinate = 0.0;
    Y_coordinate = 0.0;
}

// Normal constructor creates a custom Point object.
Point::Point( double X, double Y )
{
    X_coordinate = X;
    Y_coordinate = Y;
}

// Copy constructor creates a clone of a Point object.
Point::Point( Point & point )
{
    X_coordinate = point.X_coordinate;
    Y_coordinate = point.Y_coordinate;
}

// Setter changes the value of the X_coordinate.
void Point::setX( double X )
{
    X_coordinate = X;
}

// Setter changes the value of the Y_coordinate.
void Point::setY( double Y )
{
    Y_coordinate = Y;
}

// Getter returns the value of the X_coordinate.
double Point::getX()
{
    return X_coordinate;
}

// Getter returns the value of the Y_coordinate.
double Point::getY()
{
    return Y_coordinate;
}

// Getter computes the distance between this and another Point.
// Distance = Square_Root[ ((X2 - X1)^2) + ((X2 - X1)^2) ]
double Point::getDistance( Point & point )
{
    return sqrt( pow(X_coordinate - point.X_coordinate, 2) +
                 pow(Y_coordinate - point.Y_coordinate, 2));
}

// Getter computes the slope between this and another Point.
// Slope = (Y2 - Y1) / (X2 - X1)
double Point::getSlope( Point & point )
{
    if (X_coordinate == point.X_coordinate) return INFINITY;
    return (Y_coordinate - point.Y_coordinate)/
           (X_coordinate - point.X_coordinate);
}

// Getter prints the coordinate pair of Point in the form ( X, Y ).
// If no ostream parameter is supplied, default will be cout.
void Point::print( ostream & output )
{
    output << "(" << X_coordinate << "," << Y_coordinate << ")";
}

// Friend function behaves like Points's print method.
// Overloads the ostream operator.
// Friend is NOT a member of Point, but has access to its members.
ostream & operator << ( ostream & output, Point & point )
{
    point.print( output );
    return output;
}

//*************************************************************
// End of File
//*************************************************************

Quadrilateral.h

This file declares the attributes and behaviors of the Quadrilateral class.

//*************************************************************
//  Quadrilateral.h
//  Inheritance
//
//  Created by Karlina Beringer on July 8, 2014.
//
//  This header file contains the Quadrilateral class declaration.
//  Quadrilateral is the base class for an inheritance chain.
//  Quadrilateral includes Point through composition.
//*************************************************************

#ifndef Quadrilateral_h
#define Quadrilateral_h
#include "Point.h"

//-----------------------------------------------------------------------------
// Quadrilateral represents a four-sided polygon whose vertices can be
// circumscribed on a circle such that we get one area rather than two
// triangles touching each other at a single point.
//-----------------------------------------------------------------------------
class Quadrilateral
{
protected:
    
    // Points are accessible only by Quadrilateral and its descendents.
    Point A, B, C, D;
    
    // A brief description of the class.
    const string TYPE = "QUADRILATERAL";

    // Determines whether the quadrilateral is cyclic using
    // Ptolemy's Theorem:
    //    If AB × CD + BC × DA = AC × BD,
    //    where AB, CD, BC, and DA are side lengths,
    //    Then the quadrilateral ABCD is cyclic.
    bool isCyclicQuadrilateral();
    
public:
    // Default constructor initializes all Points to default values.
    Quadrilateral();
    
    // Normal constructor assigns Points to the parameter values.
    Quadrilateral( Point A, Point B, Point C, Point D );
    
    // Copy constructor creates a clone of Quadrilateral object.
    Quadrilateral( Quadrilateral & quadrilateral );
    
    // Getter returns the perimeter of this Quadrilateral.
    // Perimeter = sum of all side lengths.
    double getPerimeter();
    
    // Getter returns the area of this Quadrilateral.
    double getArea();
    
    // Print the contents of this Quadrilateral.
    // If no ostream parameter is supplied, default will be cout.
    void print( ostream & output = cout );
    
    // Friend function behaves like Quadrilateral's print method.
    // Overloads the ostream operator.
    // Friend is NOT a member of this class, but has access to its members.
    friend ostream & operator << ( ostream & output, Quadrilateral & quad );
};

#endif

//*************************************************************
// End of File
//*************************************************************

Quadrilateral.cpp

This file contains the method definitions of the Quadrilateral class.

//*****************************************************************
//  Quadrilateral.cpp
//  Inheritance
//
//  Created by Karlina Beringer on July 8, 2014.
//
//  This source file contains the Quadrilateral class definition.
//  Quadrilateral is the base class for an inheritance chain.
//  Quadrilateral includes Point through composition.
//*****************************************************************

#include "Quadrilateral.h"

// Determines whether the quadrilateral is cyclic using
// Ptolemy's Theorem:
//    If AB × CD + BC × DA = AC × BD,
//    where AB, CD, BC, and DA are side lengths,
//    Then the quadrilateral ABCD is cyclic.
bool Quadrilateral::isCyclicQuadrilateral()
{
    double AB = A.getDistance( B );
    double BC = B.getDistance( C );
    double CD = C.getDistance( D );
    double DA = D.getDistance( A );
    if ( (AB * CD * BC * DA) == (AC * BD) ) return true;
    return false;
}

// Default constructor initializes all Points to default values.
Quadrilateral::Quadrilateral()
{
    A = Point( 0, 0 );
    B = Point( 1, 1 );
    C = Point( 2, 1 );
    D = Point( 3, -1 );
}

// Normal constructor assigns Points to the parameter values.
Quadrilateral::Quadrilateral( Point A, Point B, Point C, Point D )
{
    if ( isCyclicQuadrilateral() )
    {
        this -> A = Point( A );
        this -> B = Point( B );
        this -> C = Point( C );
        this -> D = Point( D );
    }
    else
    {
        this -> A = Point( 0, 0 );
        this -> B = Point( 1, 1 );
        this -> C = Point( 2, 1 );
        this -> D = Point( 3, -1 );
    }
}

// Copy constructor creates a clone of Quadrilateral object.
Quadrilateral::Quadrilateral( Quadrilateral & quadrilateral )
{
    A = quadrilateral.A;
    B = quadrilateral.B;
    C = quadrilateral.C;
    D = quadrilateral.D;
}

// Getter returns the perimeter of this Quadrilateral.
// Perimeter = sum of all side lengths.
double Quadrilateral::getPerimeter()
{
    return ( A.getDistance( B ) + B.getDistance( C ) +
             C.getDistance( D ) + D.getDistance( A ) );
}

// Getter returns the area of this Quadrilateral.
// 1. Divide the quadrilateral into two triangles.
// 2. Use Heron's Formula to compute the area of
//    each triangle.
// 3. Return the sum of the two triangle areas to get
//    the area of the quadrilateral.
// --------------------------------------------------------
// Heron's Formula:
//    Let A, B, and C be the side lengths of a triangle.
//    Let S = ( A + B + C ) / 2
//    Then we can compute the area of the triangle:
//    Area = sqrt[ S*( S - A )*( S - B )*( S - C ) ]
// --------------------------------------------------------
double Quadrilateral::getArea()
{
    // First Triangle
    double AB = A.getDistance( B );
    double BC = B.getDistance( C );
    double CA = C.getDistance( A );
    
    // Second Triangle
    double AC = A.getDistance( C );
    double CD = C.getDistance( D );
    double DA = D.getDistance( A );
    
    // Compute half the perimeters.
    double S1 = ( AB + BC + CA ) / 2;
    double S2 = ( AC + CD + DA ) / 2;
    
    // Compute the areas using Heron's formula.
    double A1 = sqrt( S1*( S1-AB )*( S1-BC )*( S1-CA ));
    double A2 = sqrt( S2*( S2-AC )*( S2-CD )*( S2-DA ));
    
    // Return the sum of the two triangles.
    return A1 + A2;
}

// Print the contents of this Quadrilateral.
// If no ostream parameter is supplied, default will be cout.
void Quadrilateral::print( ostream & output )
{
    output << "--------------n";
    output << TYPE << "n";
    output << "--------------n";
    output << "Points:n";
    output << "tA = " << A << "n";
    output << "tB = " << B << "n";
    output << "tC = " << C << "n";
    output << "tD = " << D << "n";
    output << "Side Lengths:n";
    output << "tAB = " << A.getDistance( B ) << "n";
    output << "tBC = " << B.getDistance( C ) << "n";
    output << "tCD = " << C.getDistance( D ) << "n";
    output << "tDA = " << D.getDistance( A ) << "n";
    output << "Shape Properties:n";
    output << "tPerimeter = " << getPerimeter() << "n";
    output << "tArea = " << getArea() << "nn";
}

// Friend function behaves like Quadrilateral's print method.
// Overloads the ostream operator.
// Friend is NOT a member of this class, but has access to its members.
ostream & operator << ( ostream & output, Quadrilateral & quad )
{
    quad.print( output );
    return output;
}

//*****************************************************************
// End of File
//*****************************************************************

Trapezoid.h

This file declares the attributes and behaviors of the Trapezoid class.

//*****************************************************************
//  Trapezoid.h
//  Inheritance
//
//  Created by Karlina Beringer on July 10, 2014.
//
//  This header file contains the Trapezoid class declaration.
//  Trapezoid is derived from the Quadrilateral class.
//*****************************************************************

#ifndef Trapezoid_h
#define Trapezoid_h
#include "Quadrilateral.h"

//-----------------------------------------------------------------------------
// Trapezoid represents a quadrilateral with exactly least two parallel sides.
//-----------------------------------------------------------------------------
class Trapezoid: public Quadrilateral
{
// Trapezoid inherits the data members and methods of Quadrilateral.
private:
    
    // Base1 is the longest parallel edge.
    // Base2 is the shortest parellel edge.
    // Height is the distance between parallel edges.
    double base1, base2, height;
    
    // A brief description of the class.
    const string TYPE = "QUADRILATERAL/TRAPEZOID";
    
    // Helper method forces exactly two sides to be parallel.
    void setAttributes();
    
public:
    
    // Default constructor calls Quadrilateral's default constructor.
    Trapezoid();
    
    // Normal constructor calls Quadrilateral's normal constructor.
    Trapezoid( Point A, Point B, Point C, Point D );
    
    // Copy constructor calls Quadrilateral's copy constructor.
    Trapezoid( Quadrilateral & quad );
    
    // Getter returns the area of this Quadrilateral.
    // Override the method to customize it for Trapezoid.
    // Area = [(Base1 + Base2) * Height] / 2
    double getArea();
    
    // Print the contents of this Quadrilateral.
    // Override the method to customize it for Trapezoid.
    // If no ostream parameter is supplied, default will be cout.
    void print( ostream & output = cout );
    
    // Friend function behaves like Trapezoid's print method.
    // Overloads the ostream operator.
    // Friend is NOT a member of this class, but has access to its members.
    friend ostream & operator << ( ostream & output, Trapezoid & trap );
};

#endif

//*****************************************************************
// End of File
//*****************************************************************

Trapezoid.cpp

This file contains the method definitions of the Trapezoid class.

//*****************************************************************
//  Trapezoid.cpp
//  Inheritance
//
//  Created by Karlina Beringer on July 10, 2014.
//
//  This source file contains the Trapezoid class definition.
//  Trapezoid is derived from the Quadrilateral class.
//*****************************************************************

#include "Trapezoid.h"

// Helper method forces exactly two sides to be parallel.
void Trapezoid::setAttributes()
{
    // Check that only AB and CD are parallel
    // or else that only BC and DA are parallel; not both!
    double slope_AB = A.getSlope( B );
    double slope_CD = C.getSlope( D );
    double slope_BC = B.getSlope( C );
    double slope_AD = A.getSlope( D );
    if (!(slope_AB == slope_CD xor slope_BC == slope_AD))
    {
        A = Point( 0, 0 );
        B = Point( 1, 1 );
        C = Point( 3, 1 );
        D = Point( 5, 0 );
    }
    
    // Set Trapezoid-specific attributes.
    if (slope_AB == slope_CD)
    {
        if (A.getDistance( B ) > C.getDistance( D ))
        {
            base1 = A.getDistance( B );
            base2 = C.getDistance( D );
        }
        else
        {
            base1 = C.getDistance( D );
            base2 = A.getDistance( B );
        }
        height = B.getDistance( C );
    }
    else
    {
        if (B.getDistance( C ) > D.getDistance( A ))
        {
            base1 = B.getDistance( C );
            base2 = D.getDistance( A );
        }
        else
        {
            base1 = D.getDistance( A );
            base2 = B.getDistance( C );
        }
        height = A.getDistance( B );
    }
}

// Default constructor calls Quadrilateral's default constructor.
Trapezoid::Trapezoid(): Quadrilateral()
{
    setAttributes();
}

// Normal constructor calls Quadrilateral's normal constructor.
Trapezoid::Trapezoid( Point A, Point B, Point C, Point D ):
Quadrilateral( A, B, C, D )
{
    setAttributes();
}

// Copy constructor calls Quadrilateral's copy constructor.
Trapezoid::Trapezoid( Quadrilateral & quad ): Quadrilateral( quad )
{
    setAttributes();
}

// Getter returns the area of this Quadrilateral.
// Override the method to customize it for Trapezoid.
// Area = [(Base1 + Base2) * Height] / 2
double Trapezoid::getArea()
{
    return (( base1 + base2 ) * height) / 2;
}

// Print the contents of this Quadrilateral.
// Override the method to customize it for Trapezoid.
// If no ostream parameter is supplied, default will be cout.
void Trapezoid::print( ostream & output )
{
    output << "------------------------n";
    output << TYPE << "n";
    output << "------------------------n";
    output << "Points:n";
    output << "tA = " << A << "n";
    output << "tB = " << B << "n";
    output << "tC = " << C << "n";
    output << "tD = " << D << "n";
    output << "Side Lengths:n";
    output << "tAB = " << A.getDistance( B ) << "n";
    output << "tBC = " << B.getDistance( C ) << "n";
    output << "tCD = " << C.getDistance( D ) << "n";
    output << "tDA = " << D.getDistance( A ) << "n";
    output << "Shape Properties:n";
    output << "tbase1= " << base1 << "n";
    output << "tbase2 = " << base2 << "n";
    output << "theight = " << height << "n";
    output << "tPerimeter = " << getPerimeter() << "n";
    output << "tArea = " << getArea() << "nn";
}

// Friend function behaves like Trapezoid's print method.
// Overloads the ostream operator.
// Friend is NOT a member of this class, but has access to its members.
ostream & operator << ( ostream & output, Trapezoid & trap )
{
    trap.print( output );
    return output;
}

//*****************************************************************
// End of File
//*****************************************************************

Rectangle.h

This file declares the attributes and behaviors of the Rectangle class.

//*****************************************************************
//  Rectangle.h
//  Inheritance
//
//  Created by Karlina Beringer on July 9, 2014.
//
//  This header file contains the Rectangle class declaration.
//  Rectangle is derived from the Quadrilateral class.
//*****************************************************************

#ifndef Rectangle_h
#define Rectangle_h
#include "Quadrilateral.h"

//-------------------------------------------------------------------------
// Rectangle represents a quadrilateral whose sides form 90-degree angles.
//-------------------------------------------------------------------------
class Rectangle: public Quadrilateral
{
// Rectangle inherits the data members and methods of Quadrilateral.
protected:
    
    // width and length are adjacent sides that form a right angle.
    double width, length;
    
    // A brief description of the class.
    const string TYPE = "QUADRILATERAL/RECTANGLE";
    
    // Helper method forces sides to form 90-degree angles.
    void setAttributes();
    
public:
    // Default constructor calls Quadrilateral's default constructor.
    Rectangle();
    
    // Normal constructor calls Quadrilateral's normal constructor.
    Rectangle( Point A, Point B, Point C, Point D );
    
    // Copy constructor calls Quadrilateral's copy constructor.
    Rectangle( Quadrilateral & quad );
    
    // Getter returns the area of this Quadrilateral.
    // Override the method to customize it for Rectangle.
    // Area = Length * Width
    double getArea();
    
    // Getter returns the perimeter of this Quadrilateral.
    // Override the method to customize it for Rectangle.
    // Perimeter = (Length + Width) * 2
    double getPerimeter();
    
    // Print the contents of this Quadrilateral.
    // Override the method to customize it for Rectangle.
    // If no ostream parameter is supplied, default will be cout.
    void print( ostream & output = cout );
    
    // Friend function behaves like Rectangle's print method.
    // Overloads the ostream operator.
    // Friend is NOT a member of this class, but has access to its members.
    friend ostream & operator << ( ostream & output, Rectangle & rect );
};

#endif

//*****************************************************************
// End of File
//*****************************************************************

Rectangle.cpp

This file contains the method definitions of the Rectangle class.

//*****************************************************************
//  Rectangle.cpp
//  Inheritance
//
//  Created by Karlina Beringer on July 9, 2014.
//
//  This source file contains the Rectangle class definition.
//  Rectangle is derived from the Quadrilateral class.
//*****************************************************************

#include "Rectangle.h"

// Helper method forces sides to form 90-degree angles.
void Rectangle::setAttributes()
{
    double AB = A.getDistance( B );
    double BC = B.getDistance( C );
    double CD = C.getDistance( D );
    double DA = D.getDistance( A );
    
    // Check if sides AB and CD are the same length.
    // Check if sides BC and AD are the same length.
    bool lengthTest = (AB == CD && BC == DA);
    
    // Check if sides AB and CD are perpendicular.
    // Check if sides BC and AD are perpendicular.
    double slope_AB = A.getSlope( B );
    double slope_CD = C.getSlope( D );
    double slope_BC = B.getSlope( C );
    double slope_AD = A.getSlope( D );
    bool slopeTest = (slope_AB == slope_CD && slope_BC == slope_AD);
    
    // If conditions are not met, set values to default.
    if (!lengthTest || !slopeTest)
    {
        A = Point( 0, 0 );
        B = Point( 0, 5 );
        C = Point( 6, 5 );
        D = Point( 6, 0 );
    }
    
    // Set Rectangle-specific attributes.
    width = A.getDistance( B );
    length = A.getDistance( D );
}

// Default constructor calls Quadrilateral's default constructor.
Rectangle::Rectangle(): Quadrilateral()
{
    setAttributes();
}

// Normal constructor calls Quadrilateral's normal constructor.
Rectangle::Rectangle( Point A, Point B, Point C, Point D ):
Quadrilateral ( A, B, C, D )
{
    setAttributes();
}

// Copy constructor calls Quadrilateral's copy constructor.
Rectangle::Rectangle( Quadrilateral & quad ): Quadrilateral( quad )
{
    setAttributes();
}

// Getter returns the area of this Quadrilateral.
// Override the method to customize it for Rectangle.
// Area = Length * Width
double Rectangle::getArea()
{
    return length * width;
}

// Getter returns the perimeter of this Quadrilateral.
// Override the method to customize it for Rectangle.
// Perimeter = (Length + Width) * 2
double Rectangle::getPerimeter()
{
    return (length + width) * 2;
}

// Print the contents of this Quadrilateral.
// Override the method to customize it for Rectangle.
void Rectangle::print( ostream & output )
{
    output << "------------------------n";
    output << TYPE << "n";
    output << "------------------------n";
    output  << "Points:n";
    output << "tA = " << A << "n";
    output << "tB = " << B << "n";
    output << "tC = " << C << "n";
    output << "tD = " << D << "n";
    output << "Side Lengths:n";
    output << "tAB = " << A.getDistance( B ) << "n";
    output << "tBC = " << B.getDistance( C ) << "n";
    output << "tCD = " << C.getDistance( D ) << "n";
    output << "tDA = " << D.getDistance( A ) << "n";
    output << "Shape Properties:n";
    output << "twidth = " << width << "n";
    output << "tlength = " << length << "n";
    output << "tPerimeter = " << getPerimeter() << "n";
    output << "tArea = " << getArea() << "nn";
}

// Friend function behaves like Rectangle's print method.
// Overloads the ostream operator.
// Friend is NOT a member of this class, but has access to its members.
ostream & operator << ( ostream & output, Rectangle & rect )
{
    rect.print( output );
    return output;
}

//*****************************************************************
// End of File
//*****************************************************************

Square.h

This file declares the attributes and behaviors of the Square class.

//*****************************************************************
//  Square.h
//  Inheritance
//
//  Created by Karlina Beringer on July 10, 2014.
//
//  This header file contains the Square class declaration.
//  Square is derived from the Rectangle class.
//*****************************************************************

#ifndef Square_h
#define Square_h
#include "Rectangle.h"

//---------------------------------------------------------------------------
// Square represents a rectangle whose length and width are the same length.
//---------------------------------------------------------------------------
class Square: public Rectangle
{
    
// Square inherits the data members and methods of Quadrilateral.
private:
    
    // A brief description of the class.
    const string TYPE = "QUADRILATERAL/RECTANGLE/SQUARE";
    
    // Helper method forces length and width to be the same length.
    void setAttributes();

public:
    
    // Default constructor calls Rectangle's default constructor.
    Square();
    
    // Normal constructor calls Rectangle's normal constructor.
    Square( Point A, Point B, Point C, Point D );
    
    // Copy constructor calls Quadrilateral's copy constructor.
    Square( Quadrilateral & quad );
    
    // Getter returns the perimeter of this Rectangle.
    // Override the method to customize it for Square.
    // Perimeter =  Length * 4
    double getPerimeter();
    
    // Getter returns the area of this Rectangle.
    // Override the method to customize it for Square.
    // Area = Length * Length
    double getArea();
    
    // Print the contents of this Rectangle.
    // Override the method to customize it for Square.
    // If no ostream parameter is supplied, default will be cout.
    void print( ostream & output = cout );
    
    // Friend function behaves like Square's print method.
    // Overloads the ostream operator.
    // Friend is NOT a member of this class, but has access to its members.
    friend ostream & operator << ( ostream & output, Square & sqr );
};


#endif

//*****************************************************************
// End of File
//*****************************************************************

Square.cpp

This file contains the method definitions of the Square class.

//*****************************************************************
//  Square.cpp
//  Inheritance
//
//  Created by Karlina Beringer on July 10, 2014.
//
//  This source file contains the Square class definition.
//  Square is derived from the Rectangle class.
//*****************************************************************

#include "Square.h"

// Helper method forces length and width to be the same length.
void Square::setAttributes()
{
    // Call the setAttributes method from the parent class.
    Rectangle::setAttributes();
    
    //setAttributes();
    if (length != width)
    {
        A = Point( 0, 0 );
        B = Point( 0, 5 );
        C = Point( 5, 5 );
        D = Point( 5, 0 );
    }
    width = 5;
    length = 5;
}

// Default constructor calls Rectangle's default constructor.
Square::Square(): Rectangle()
{
    setAttributes();
}

// Normal constructor calls Rectangle's normal constructor.
Square::Square( Point A, Point B, Point C, Point D ):
Rectangle( A, B, C, D )
{
    setAttributes();
}

// Copy constructor calls Rectangle's copy constructor.
Square::Square( Quadrilateral & quad ): Rectangle( quad )
{
    setAttributes();
}

// Getter returns the perimeter of this Rectangle.
// Override the method to customize it for Square.
// Perimeter =  Length * 4
double Square::getPerimeter()
{
    return length * 4;
}

// Getter returns the area of this Rectangle.
// Override the method to customize it for Square.
// Area = Length * Length
double Square::getArea()
{
    return length * length;
}

// Print the contents of this Rectangle.
// Override the method to customize it for Square.
// If no ostream parameter is supplied, default will be cout.
void Square::print( ostream & output )
{
    cout << "--------------------------------n";
    output << TYPE << "n";
    cout << "--------------------------------n";
    output << "Points:n";
    output << "tA = " << A << "n";
    output << "tB = " << B << "n";
    output << "tC = " << C << "n";
    output << "tD = " << D << "n";
    output << "Side Lengths:n";
    output << "tAB = " << A.getDistance( B ) << "n";
    output << "tBC = " << B.getDistance( C ) << "n";
    output << "tCD = " << C.getDistance( D ) << "n";
    output << "tDA = " << D.getDistance( A ) << "n";
    output << "Shape Properties:n";
    output << "tlength = " << length << "n";
    output << "tPerimeter = " << getPerimeter() << "n";
    output << "tArea = " << getArea() << "nn";
}

// Friend function behaves like Square's print method.
// Overloads the ostream operator.
// Friend is NOT a member of this class, but has access to its members.
ostream & operator << ( ostream & output, Square & sqr )
{
    sqr.print( output );
    return output;
}

//*****************************************************************
// End of File
//*****************************************************************

main.cpp

This file contains the driver of the Quadrilateral classes.

//*****************************************************************
//  main.cpp
//  Inheritance
//
//  Created by Karlina Beringer on July 8, 2014.
//
//  This driver implements the Quadrilateral class and its
//  derived and classes, Rectangle, Trapezoid, and Square.
//  Quadrilateral includes Point through composition.
//*****************************************************************

#include "Quadrilateral.h"
#include "Rectangle.h"
#include "Trapezoid.h"
#include "Square.h"

int main()
{
    //*****************************************************************
    // Point Tests
    //*****************************************************************
    cout << "---------------------------n";
    cout << "Point Tests...n";
    cout << "---------------------------nn";
    
    // Create a default Point object.
    Point A;
    cout << "tDefault Point, A = ";
    cout << A << "n";
    
    // Create a custom Point object.
    Point B( 1, 1 );
    cout << "tCustom Point, B = ";
    cout << B << "n";
    
    // Create a copy of Point A and call it C.
    Point C( A );
    cout << "tCopy of Point A, named C = ";
    cout << C << "n";
    
    // Reset the values of Point C.
    C.setX( 2 );
    C.setY( 0 );
    cout << "tReset C to ";
    cout << C << "n";
    
    // Get the slope of the line between A and B.
    cout << "tSlope AB = ";
    cout << A.getSlope( B ) << "n";
    
    // Get the distance between A and B.
    cout << "tDistance AB = ";
    cout << A.getDistance( B ) << "n";
    
    // Get the slope of the line between A and C.
    cout << "tSlope AC = ";
    cout << A.getSlope( C ) << "n";
    
    // Get the distance between A and C.
    cout << "tDistance AC = ";
    cout << A.getDistance( C ) << "nn";
    
    //*****************************************************************
    // Quadrilateral Tests
    //*****************************************************************
    cout << "---------------------------n";
    cout << "Quadrilateral Tests...n";
    cout << "---------------------------nn";
    
    // Create a default Quadrilateral object.
    Quadrilateral quad1;
    cout << "tDefault Quadrilateral...n";
    cout << quad1;
    
    // Create a copy Quadrilateral object.
    Quadrilateral quad2( quad1 );
    cout << "tCopy Quadrilateral...n";
    cout << quad2;
    
    // Create a custom Quadrilateral object.
    cout << "tCustom Quadrilateral...n";
    Point W( -1, -1 ), X( 0, 2 ), Y( 2, 2 ), Z( 4, 0 );
    Quadrilateral quad3( W, X, Y, Z );
    cout << quad3;
    
    //*****************************************************************
    // Trapezoid Tests
    //*****************************************************************
    cout << "---------------------------n";
    cout << "Trapezoid Tests...n";
    cout << "---------------------------nn";
    
    // Create a default Trapezoid object.
    Trapezoid trap1;
    cout << "tDefault Trapezoid...n";
    cout << trap1;
    
    // Create a copy Trapezoid object from Quadrilateral object.
    Trapezoid trap2( quad1 );
    cout << "tCopy Trapezoid from Quadrilateral...n";
    cout << trap2;
    
    // Create a copy Trapezoid object from Trapezoid object.
    Trapezoid trap3( trap1 );
    cout << "tCopy Trapezoid from Trapezoid...n";
    cout << trap3;
    
    // Create a custom Trapezoid object.
    cout << "tCustom Trapezoid...n";
    Trapezoid trap5( W, X, Y, Z );
    cout << trap5;
    
    //*****************************************************************
    // Rectangle Tests
    //*****************************************************************
    cout << "---------------------------n";
    cout << "Rectangle Tests...n";
    cout << "---------------------------nn";
    
    // Create a default Rectangle object.
    Rectangle rect1;
    cout << "tDefault Rectangle...n";
    cout << rect1;
    
    // Create a copy Rectangle object from Quadrilateral object.
    Rectangle rect2( quad1 );
    cout << "tCopy Rectangle from Quadrilateral...n";
    cout << rect2;
    
    // Create a copy Rectangle object from Rectangle object.
    Rectangle rect3( rect1 );
    cout << "tCopy Rectangle from Rectangle...n";
    cout << rect3;
    
    // Create a custom Rectangle object.
    cout << "tCustom Rectangle...n";
    Rectangle rect4( W, X, Y, Z );
    cout << rect4;
    
    //*****************************************************************
    // Square Tests
    //*****************************************************************
    cout << "---------------------------n";
    cout << "Square Tests...n";
    cout << "---------------------------nn";
    
    // Create a default Square object.
    Square sqr1;
    cout << "tDefault Square...n";
    cout << sqr1;
    
    // Create a copy Square object from Quadrilateral object.
    Square sqr2( quad1 );
    cout << "tCopy Square from Quadrilateral...n";
    cout << sqr2;
    
    // Create a copy Square object from Rectangle object.
    Square sqr3( rect1 );
    cout << "tCopy Square from Rectangle...n";
    cout << sqr3;
    
    // Create a copy Square object from Square object.
    Square sqr4( sqr1 );
    cout << "tCopy Square from Square...n";
    cout << sqr4;
    
    // Create a custom Square object.
    cout << "tCustom Square...n";
    Square sqr5( W, X, Y, Z );
    cout << sqr5;
    
    // Terminate program
    return 0;
}

//*****************************************************************
// End of File
//*****************************************************************

Output.txt

This file contains the program output after execution.

---------------------------
Point Tests...
---------------------------

	Default Point, A = (0,0)
	Custom Point, B = (1,1)
	Copy of Point A, named C = (0,0)
	Reset C to (2,0)
	Slope AB = 1
	Distance AB = 1.41421
	Slope AC = -0
	Distance AC = 2

---------------------------
Quadrilateral Tests...
---------------------------

	Default Quadrilateral...
--------------
QUADRILATERAL
--------------
Points:
	A = (0,0)
	B = (1,1)
	C = (2,1)
	D = (3,-1)
Side Lengths:
	AB = 1.41421
	BC = 1
	CD = 2.23607
	DA = 3.16228
Shape Properties:
	Perimeter = 7.81256
	Area = 3

	Copy Quadrilateral...
--------------
QUADRILATERAL
--------------
Points:
	A = (0,0)
	B = (1,1)
	C = (2,1)
	D = (3,-1)
Side Lengths:
	AB = 1.41421
	BC = 1
	CD = 2.23607
	DA = 3.16228
Shape Properties:
	Perimeter = 7.81256
	Area = 3

	Custom Quadrilateral...
--------------
QUADRILATERAL
--------------
Points:
	A = (-1,-1)
	B = (0,2)
	C = (2,2)
	D = (4,0)
Side Lengths:
	AB = 3.16228
	BC = 2
	CD = 2.82843
	DA = 5.09902
Shape Properties:
	Perimeter = 13.0897
	Area = 9

---------------------------
Trapezoid Tests...
---------------------------

	Default Trapezoid...
------------------------
QUADRILATERAL/TRAPEZOID
------------------------
Points:
	A = (0,0)
	B = (1,1)
	C = (3,1)
	D = (5,0)
Side Lengths:
	AB = 1.41421
	BC = 2
	CD = 2.23607
	DA = 5
Shape Properties:
	base1= 5
	base2 = 2
	height = 1.41421
	Perimeter = 10.6503
	Area = 4.94975

	Copy Trapezoid from Quadrilateral...
------------------------
QUADRILATERAL/TRAPEZOID
------------------------
Points:
	A = (0,0)
	B = (1,1)
	C = (3,1)
	D = (5,0)
Side Lengths:
	AB = 1.41421
	BC = 2
	CD = 2.23607
	DA = 5
Shape Properties:
	base1= 5
	base2 = 2
	height = 1.41421
	Perimeter = 10.6503
	Area = 4.94975

	Copy Trapezoid from Trapezoid...
------------------------
QUADRILATERAL/TRAPEZOID
------------------------
Points:
	A = (0,0)
	B = (1,1)
	C = (3,1)
	D = (5,0)
Side Lengths:
	AB = 1.41421
	BC = 2
	CD = 2.23607
	DA = 5
Shape Properties:
	base1= 5
	base2 = 2
	height = 1.41421
	Perimeter = 10.6503
	Area = 4.94975

	Custom Trapezoid...
------------------------
QUADRILATERAL/TRAPEZOID
------------------------
Points:
	A = (0,0)
	B = (1,1)
	C = (3,1)
	D = (5,0)
Side Lengths:
	AB = 1.41421
	BC = 2
	CD = 2.23607
	DA = 5
Shape Properties:
	base1= 5
	base2 = 2
	height = 1.41421
	Perimeter = 10.6503
	Area = 4.94975

---------------------------
Rectangle Tests...
---------------------------

	Default Rectangle...
------------------------
QUADRILATERAL/RECTANGLE
------------------------
Points:
	A = (0,0)
	B = (0,5)
	C = (6,5)
	D = (6,0)
Side Lengths:
	AB = 5
	BC = 6
	CD = 5
	DA = 6
Shape Properties:
	width = 5
	length = 6
	Perimeter = 22
	Area = 30

	Copy Rectangle from Quadrilateral...
------------------------
QUADRILATERAL/RECTANGLE
------------------------
Points:
	A = (0,0)
	B = (0,5)
	C = (6,5)
	D = (6,0)
Side Lengths:
	AB = 5
	BC = 6
	CD = 5
	DA = 6
Shape Properties:
	width = 5
	length = 6
	Perimeter = 22
	Area = 30

	Copy Rectangle from Rectangle...
------------------------
QUADRILATERAL/RECTANGLE
------------------------
Points:
	A = (0,0)
	B = (0,5)
	C = (6,5)
	D = (6,0)
Side Lengths:
	AB = 5
	BC = 6
	CD = 5
	DA = 6
Shape Properties:
	width = 5
	length = 6
	Perimeter = 22
	Area = 30

	Custom Rectangle...
------------------------
QUADRILATERAL/RECTANGLE
------------------------
Points:
	A = (0,0)
	B = (0,5)
	C = (6,5)
	D = (6,0)
Side Lengths:
	AB = 5
	BC = 6
	CD = 5
	DA = 6
Shape Properties:
	width = 5
	length = 6
	Perimeter = 22
	Area = 30

---------------------------
Square Tests...
---------------------------

	Default Square...
--------------------------------
QUADRILATERAL/RECTANGLE/SQUARE
--------------------------------
Points:
	A = (0,0)
	B = (0,5)
	C = (5,5)
	D = (5,0)
Side Lengths:
	AB = 5
	BC = 5
	CD = 5
	DA = 5
Shape Properties:
	length = 5
	Perimeter = 20
	Area = 25

	Copy Square from Quadrilateral...
--------------------------------
QUADRILATERAL/RECTANGLE/SQUARE
--------------------------------
Points:
	A = (0,0)
	B = (0,5)
	C = (5,5)
	D = (5,0)
Side Lengths:
	AB = 5
	BC = 5
	CD = 5
	DA = 5
Shape Properties:
	length = 5
	Perimeter = 20
	Area = 25

	Copy Square from Rectangle...
--------------------------------
QUADRILATERAL/RECTANGLE/SQUARE
--------------------------------
Points:
	A = (0,0)
	B = (0,5)
	C = (5,5)
	D = (5,0)
Side Lengths:
	AB = 5
	BC = 5
	CD = 5
	DA = 5
Shape Properties:
	length = 5
	Perimeter = 20
	Area = 25

	Copy Square from Square...
--------------------------------
QUADRILATERAL/RECTANGLE/SQUARE
--------------------------------
Points:
	A = (0,0)
	B = (0,5)
	C = (5,5)
	D = (5,0)
Side Lengths:
	AB = 5
	BC = 5
	CD = 5
	DA = 5
Shape Properties:
	length = 5
	Perimeter = 20
	Area = 25

	Custom Square...
--------------------------------
QUADRILATERAL/RECTANGLE/SQUARE
--------------------------------
Points:
	A = (0,0)
	B = (0,5)
	C = (5,5)
	D = (5,0)
Side Lengths:
	AB = 5
	BC = 5
	CD = 5
	DA = 5
Shape Properties:
	length = 5
	Perimeter = 20
	Area = 25

Program ended with exit code: 0

References

  1. Area of a Trapezoid. Mrs. Glossers Math Goodies. A Hotchalk/Glam Partner Site. 2014.http://www.mathgoodies.com/lessons/vol1/area_trapezoid.html
  2. Friendship and Inheritance. cplusplus.com. 2014. http://www.cplusplus.com/doc/tutorial/inheritance/
  3. Herons Formula. MathIsFun.com. 2012. http://www.mathsisfun.com/geometry/herons-formula.html
  4. Stapel, Elizabeth.Slope: Parallel and Perpendicular Lines. Purplemath. 2014. http://www.purplemath.com/modules/slope2.htm
  5. Stapel, Elizabeth.The Distance Formula. Purplemath. 2014. http://www.purplemath.com/modules/distform.htm
  6. Weisstein, Eric W. Ptolemys Theorem. MathWorld. Wolfram Mathematica. 2014. http://mathworld.wolfram.com/PtolemysTheorem.html

Categories: mathtechnologytutorials