INFORMATION FROM DR. EBRAHIMI'S C++ PROGRAMING EASY WAYS

Home                  ABOUT US                    CONTACT US                  TUTORIAL

CHAPTER 16

 

INHERITANCE:

REUSABILITY AND EXTENDABILITY

 

 

The world around us is made of objects that share many similarities. These similarities can be classified into common groups. For example, in biology taxonomy organisms are classified into a hierarchy of group, from general to specific. In C++, objects are created from classes; and a class may share (inherit) some common data members and member functions that belong to another class or classes. As a result, a new class can be created based on an existing class rather than creating it from scratch. An inherited class can have its own data and function members and can modify or override the inherited members. Inheritance is an important tool of Object-Oriented Programming (OOP), because it promotes reusability and ease of extensibility by building on what is already there and customizing it as desired. A programmer can build a hierarchy that goes from a general class to a specific class by incorporating inheritance. With class hierarchy a program is easier to follow, debug, and modify. With inheritance, a class is built on an existing class that has already been tested; therefore, inheritance reduces the time and the cost of development as well as minimizes errors in the program. Inheritance is also known as derivation or specialization. In fact, inheritance is not something new. For example, humans have organized knowledge into hierarchical structures such as the animal kingdoms.

 

 

CLASS INHERITANCE: GENERAL SYNTAX

 

The general form of a class inherited from another class is shown in fig 9.1. The access specifier (access control) can be public, private or protected. The syntax for class inheritance is the same as a regular class except that after the class name (derivedname) there is a single colon, the derivation access type (accessspecifier), and the name of the class (baseclassname) from which it is derived.

 

 

class derivedname : accessspecifier  baseclassname{

                                    accessspecifier: memberdata;

                                    accessspecifier: memberfunctions; };

Figure 16.1 – Class inheritance syntax

 

 

 

 

 

 

 

 

EXAMPLE OF INHERITANCE

Take a moment and categorize yourself as an object.  For example, are you a full time employee, a part time student, or both?  Do you have a bank account? Do you own a car?  As human beings we categorize the objects around us into hierarchical structures. For example, livings things are divided into five kingdoms (plant, animal, fungi, etc.). Furthermore, these kingdoms are divided into smaller subcategories.  Humans belong to the kingdom Animilia, the phylum Chordata, and the class Mammilia. These classes all share some commonality such as attributes (data) and behaviors (functions) that can be factored out.

 

EMPLOYEE CLASS: An employee can belong to a base class of person and several derived classes such as a salaried or hourly paid class both of which inherit from the person class. An employee can be full time or part time. Moreover, an employee can be a consultant, manager, or executive.

 

STUDENT CLASS:  There may be different kinds of students in a college that all share common characteristics.

The student class is the base class and students can be further categorized into the following classes: 

Undergraduate

Graduate

Full time

Part time

Freshman, sophomore, junior, senior

Exchange

International student

 

For example, Jane Doe is a part time, freshman, undergraduate, exchange student.

 

 

EXAMPLE OF INHERITANCE: COMPUTE AREA OF CIRCLE

 

The following program computes the area of a circle by providing the x and y coordinates of two given points. The program finds the radius using the distance formula. The program begins by defining the class point and class circle. The circle class inherits from the point class. The class point has two member functions: setpoints( ), which initializes the coordinates, and distance( ), which computes the distance between the given the points.  The class circle inherits the distance( ) function in order to compute the area. 

 

 

 

 

Text Box: #include <iostream>
#include <cmath>
using namespace std;
class point{
public: int xstartpoint,ystartpoint;
int xendpoint, yendpoint;
void setpoints(int x1, int x2, int y1, int y2){   
                        xstartpoint = x1, xendpoint = x2;
                        ystartpoint = y1, yendpoint = y2;}
double distance(){   
                        return  sqrt((pow(xendpoint-xstartpoint,2))+(pow(yendpoint-ystartpoint,2)));} 
         };//POINT
class circle: public point{
public: double radius;
double area(){
                        radius = distance() ; //function belongs to base class
                        return radius * radius * 3.14;} };//CIRCLE
int main(){
            int x1coord = 2, y1coord = 12, x2coord= 6,y2coord = 15;      
            circle mycircle;
            mycircle.setpoints (x1coord,x2coord,y1coord,y2coord);
            cout<<"CIRCLE AREA IS "<<mycircle.area()<<endl;   
               return 0;
 }//MAIN
Text Box: CIRCLE AREA IS 78.5
Text Box: Figure 16.2a – A program showing single inheritance
Text Box: Figure 16.2b – Output of 16.2a

  

 

 

 

 

 

 

 

 

 

 

 

 

 


 

BASE CLASS, DERIVED CLASS-GENERALIZATION TO SPECIALIZATION

 

In building inheritance, the existing class is called the base class and the class that inherits from the base class is called the derived class. In the above example class point is the base class and class circle is the derived class. To determine a base class we factor out the common attributes (data) and behaviors (functions) from other classes. The factoring can continue until you get to a specific class and you want to focus and instantiate (create) an object. This leads from generalization to specialization. 

 

class D : public B {

                                    //………

                                    //………

                                                            };

 

In the preceding example, D is the derived class (or subclass) and B is the base class (or super class). Note that class D inherits the data and functions from class B, therefore class B must exist before D can inherit from it.

 

PROTECTED MEMBERS INSTEAD OF PRIVATE

 

Recall, the access controls for a member class are: private, public, and protected.  In the base class, instead of private, the keyword protected is used so that the subclasses can access it while not making it public to every other class. When an access control is specified as protected in the base class, it suggests that there will be a derived class (subclass) whose members can access the base class members as if it were private only to that derived class. Remember that in a class, the private members are only accessible directly by its members; however, the friend of the class, though not a member of the class, can access the private members. Friends of classes will be further discussed. However, by making a member of a class protected, its derived class can also access the protected member, as it is private to both the base class and the derived class.

 

Text Box: #include <iostream>
using namespace std;
class B {
protected: int bm; };
 
class D: public B {
public: accessbm(int x){ bm=x+2;} };
 
int main(){
            D ob;
            cout<<"bm VALUE IS "<<ob.accessbm(5)<<endl;
            return 0;           
}//MAIN
Text Box: bm VALUE IS 7
Text Box: Figure 16.3a – Protected base class member example
Text Box: Figure 16.3b – Output of 16.3a

  

 

 

 

 

 

 

 

 

 


 

In the above example, what would happen if the access control became private instead of protected?  The data member bm would be inaccessible.

 

 

DEFAULT INHERITANCE ACCESS TYPE: PRIVATE

 

The default inheritance access for a derived class is private, which means the non-private base class members become private for the derived class; note that the private members of the base class are not accessible in the derived class. Public and protected members of the base class become accessible by the derived class member functions when the derived access modifier is private. However, once the public and protected members of the base class become private in the derived class, these members are inaccessible to the outsider. This means that if you create an object of the derived class in the main program, it cannot access any of the members in the class. Private inheritance, though it is the default, might seem useless.  Setting the inheritance access type (control) to anything other than public, such as private or protected, will downgrade the accessibility of the base class members.  For example, if the inheritance access type is private and the access type of the base class member is public, it forces it to become private and therefore accessible only to the members of the derived class. Note that just because private members of the base class are accessible inside the derived class, it does not mean that objects of the derived class can access the members of the base class directly. The members are only accessible through the public utility functions in the derived class or friend. To summarize and settle the confusion when dealing with members of the base class in the derived class, visualize the derived class as a new class in which the base class members are included in the derived class (except private base members) but now with new access permission types from the impact of the derived class access modifier. For example, in the following program, think that the protected member bm in class B is physically present in the derived class D as private bm.

Text Box: #include <iostream>
using namespace std;
class B {
protected: int bm; };
 
class DPV: private B {
public: accessbm(int x){ bm=x+2;} };
 
int main(){
            DPV ob;
            cout<<"bm VALUE IS "<<ob.accessbm(5)<<endl;
            return 0;           
}//MAIN

  

 

 

 

 

 

 

 

 

 

 

 

 

 


 

           

Figure 16.4a – Private inheritance example

 

Text Box: bm VALUE IS 7

  

 


 

           

Figure 16.4b – Output of 16.4a

 

PRIVATE INHERITANCE

 

In the following example, the class DPV is privately derived from the base class B, making the base members that are public and protected to private. Therefore, the members of the derived class can access these inherited members. However, since these inherited members become private in the class DPV, they are no longer accessible to any other classes or any classes derived from DPV.  

 

 

 

Hosted by www.Geocities.ws

1