Skip over navigation

Classes in C++

Inheritance

Problems

Inheritance, page 2

page 1 of 3

An important feature of object-oriented programming languages is inheritance: the ability to create derived classes. Consider the following class definition:


class Polygon
{
	private:
		int num_sides;
	public:
		int get_num_sides() {return num_sides;}
		Polygon(int ns=3) {num_sides = ns;}
};

You might like to create a new class called Quad to represent a 4-sided figure; but since this is a type of polygon, it shares some of the same properties. In this simple example, num_sides might be a convenient property for the Quad class to keep track of, so you might choose to derive class Quad from class Polygon:


class Quad : public Polygon
{
	private:
		double side_length[4];
	public:
		double get_perimeter();
		Square(double side1, double side2, 
		       double side3, double side4);
		~Square();
}
double Quad::get_perimeter() {
	double perim = 0;
	for(int i = 0; i < 4; i++) 
		perim += side_length[i];	// sum the sides
	return perim;
}
Quad::Quad(double side1, double side2, double side3, double side4) : Polygon(4)
{
	side_length[0] = side1;
	side_length[1] = side2;
	side_length[2] = side3;
	side_length[3] = side4;
}
Quad::~Quad() : ~Polygon() {delete [] side_length;}

Quad is called a subclass of its superclass Polygon. Creating a derived class is similar to creating a new class, except you use the colon operator to indicate the superclass in the declaration, in the constructor, and in the destructor. Notice that in the notation for the constructor, the superclass's constructor is called with argument 4.

Any instance of a subclass has all the same member functions and data members as its superclass. Therefore Quad has a private data member num_sides and member function get_num_sides() (as well as the constructor Polygon() ). However, Quad cannot directly access its num_sides data member, even within the class definition, because the variable was declared to be private in the definition of Polygon. A superclass's private data member can only be accessed through the superclass's public member functions. If I wanted num_sides to be accessible to the Quad subclass, but still have the other properties of a private data member within Quad, I would have to declare num_sides as a protected variable in its superclass, Polygon. The protected keyword is used for any variable (or function) that should be directly accessible to subclasses, but should otherwise behave as a private data member.

Multiple inheritance is also allowed in C++. In the class definition, separate the superclasses by commas:


class MySubclass : public Superclass1, public Superclass2
{
	/* class definition */
};

Be sure to use the scope operator generously; if two classes have the same variable name or function name, you need to be specific. Consider the following:

Follow Us