Getting Started with C++: Inheritance

Author: Ronald S. Holland
at
Total Application Works






To visit my site

HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#


To contact us

© 2002 - 2016 All Rights Reserved Total Application Works


  • Tell a friend about this site (copy and paste the following HTML page into a file (e.g., using Notepad).)

  • <html>
    <head>
    <title>Example of a link </title>
    </head>
    <body>
    <a href="http://sumtotalz.com/TotalAppsWorks/CPP/CPP_Inheritance.html">
    Getting Started with C++: Inheritance </a>
    </table>
    </body>
    </html>
    Source


Read Me First

The CPP_Inheritance.zip file contains the following files:

  1. CPP_Student.c++ - this file contains the main method code and is the entry point when the program is loaded into memory,
  2. stdafx.h
  3. targetver.h
  4. CPP_Inheritance.html - is the tutorial that describes how to build the Student class programs
  5. CPP_Student.vcproj - Basically the .csproj file contains the list of files in your project, plus the references to system assemblies etc. It contains everything you need to build your project.
  6. CPP_Student.SLN
This application requires Microsoft c++ Visual Studio to run.

To run any of the projects:

  1. Go to the folder where you downloaded the CPP_Inheritance.zip compressed file
  2. Extract the files
  3. Right clck on CPP_Student.vcproj - click on the version of Microsoft studio you have
  4. When Microsoft studio IDE is started
  5. Click on the Debug menu
  6. Click on the Start without Debugging menu
    • the CPP_Student project will begin to execute

Introduction

This tutorial is intended for that person who is a beginner with object oriented programming and Inheritance. In order for you to be able to follow this tutorial, you will need a C++ compiler. I used Microsoft's Visual Studio C++ 2008 Edition . I don't believe in buying something if you can get it for free. At this point, if you don't have a compiler, you can download one for free from

If you are not familiar with Microsoft's Visual Studio C++ 2008 Edition, you can find some referrals in the next section.

Some tutorials on Microsoft's Visual Studio C++ 2008 Edition


This tutorial assumes that you have completed A basic first C++ Program tutorial. For additional information on inheritance, see the next section.

Inheritance

The ability to use the object-oriented programming is an important feature of C++. The tutorial on classes introduced the concept of the class. You should read it before continuing this tutorial if you have not read it and do not know the basic details of classes. For a brief description of classes, see the section on class.

When you derive a class from a parent class and the derived class has access to the parent's methods, it is called inheritance. In real life, you can use your DNA to trace your ancestry. Similarly, some IDEs allow you to trace the inheritance of a class. The new class created is called a derived/child class and the old class is called a base/parent class in C++. In C++ inheritance, the derived class will inherit most of the features of the base class. It should be noted that there are some exceptions in C++ inheritance that are as follows.

  • The constructor and destructor of a base class are not inherited
  • The assignment operator is not inherited
      This keeps one class from being assigned to different class e.g., apples objects being assigned to oranges objects.
  • In addition, the friend functions and friend classes of the base class are not inherited.
There are some points to be remembered regarding C++ inheritance. The protected and public variables or members of the base class can be accessed in the derived class. But, a derived class cannot access a private member in the base class.

Inheritance is an important feature of classes; basically, it is central to the idea of object-oriented programming. Inheritance allows you to create a hierarchy of classes, with various classes of more specific natures inheriting the general aspects of more generalized classes. In this way, it is possible to structure a program starting with abstract ideas that are then implemented by specific classes. What is a class?

Class

A class is an abstract data type that contains both data and functions. Let's consider the class of automobile, which contains the set of all automobiles. A sampling might be:

  • Acura TL
  • BMW 5 series
  • Buick Century
  • Ford Explorer
  • Honda Pilot
  • Mazda6
  • Toyota Avalon
  • Toyota Highlander
  • Volvo S60
  • Etc.
If we were to write one of the examples above in C++, it might look like:

  

class Toyota : automobile {
   ...
}

class Avalon : Toyota {
   ...
}
  
Figure 1: Inheritance from Automobile


This example is interpreted as derived class Avalon inherits from class Toyota and derived class Toyota inherits from class automobile. In addition, the derived class Avalon inherits from the Automobile class. We will discuss inheritance further in the next section.

Student class as a base class

For example, you might have a class student from which classes GraduateStudent, UnderGraduateStudent, HighSchoolStudent, and ElementrySchoolStudent inherit the traits/behaviors that are general to all students; at the same time, each of those classes will have attributes specific to the
  • GraduateStudent;
  • UnderGraduateStudent;
  • HighSchoolStudent; or
  • ElementrySchoolStudent.
Consider the following figure.

 
                       +-------------+
       Base Class ---> |    Student  | 
                       +------+------+
                              | Derived classes
                              v
    +---------------------+---+--------+
    |                     |            |            
+------+--------+  +------+--------+   |
|GraduateStudent|  |UnderGraduate  |   |
+---------------+  |  Student      |   |
                   +---------------+   | 
                                       |
                                       | 
                                +------+
                                | 
                        +-------+--------+
                        |                |
                +-------+-------+ +------+--------+
                |   HighSchool  | |ElementrySchool|
                |     Student   | |   Student     |   
                +---------------+ +---------------+     
 
Figure 2: Inheritance


In Figure 2, if the class Student has the following behaviors;
  1. Learn()
  2. Study()
  3. Read()
  4. Research()
  5. KissUpToTeacher()
  6. SitInClass()
  7. TakeNotes()
  8. WritePapers()
  9. WriteThesis()
  10. SleepInClass()
  11. GoToClass()
  12. GoToNextClass()
  13. GoHome()
  14. AskTeacherQuestions()
  15. GetSomethingToEat()
  16. GetSomethingToDrink()
  17. GoToPractice()
  18. ...
  19. TakeTest()
The derived classes inherit these behaviors from the base class Student. An example of this would be as follows:

 
#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std ;
using std::string ;



class Student {

   private:
      int grade ;

   public:
      string Learn() ;
      void Study() ;
      string Read() ;
      string Research() ;
      void   KissUpToTeacher( int a ) ;
      void   SitInClass() ;
      string TakeNotes() ;
      string WritePapers() ;
      string WriteThesis() ;
      void   SleepInClass() ;
      void   GoToClass() ;
      void   GoToNextClass() ;
      void   GoHome() ;
      string AskTeacherQuestions() ;
      int    GetSomethingToEat() ;
      int    GetSomethingToDrink() ;
      void   GoToPractice() ;
      int    TakeTest( string str )  ;
      int    GetGrade()  ;
      void   SetGrade( int a )  ;
} ;


class UnderGraduateStudent : public Student {

   private:
      int grade ;

   public:
      int TakeTest( string a )  ;

} ;

void Student::KissUpToTeacher( int a ) {
	string kissingUp[] = {
          "You are the best teacher ever!",
        "I have never seen a better teacher",
	"You make learning so easy.",
	"When I look up teacher in the dictionary, "
        + + I see picture of you."
	} ;	

   cout << kissingUp[ a ] << "\n" ;      
}

int Student::GetGrade() {
	SetGrade( 95 )  ;
   return grade  ;
}


void Student::SetGrade( int a) {
	grade = 95   ;
}

int UnderGraduateStudent::TakeTest( string str ) {
   return GetGrade()  ;
}


int _tmain(int argc, _TCHAR* argv[]) {

   int grade ;

   UnderGraduateStudent ogs ;

   ogs.KissUpToTeacher( 1 ) ;

   grade = ogs.TakeTest("MathTest") ; 

   cout << "My math grade was: " << grade << "\n" ;  

   ogs.KissUpToTeacher( 3 ) ;    

   return 0;
}

 
Program output


I have never seen a better teacher

My math grade was: 95

When I look up teacher in the dictionary, I see picture of you.
Figure 3: Graduate Student Inheritance


The example in Figure 3 is a basic inheritance demonstration. When you note how GetGrade() and KissUpToTeacher( int a ) are accessed, you will see the power of inheritance. This example is not intended to be an industrial strength program. It is intended to be a beginner's example. We will explore inheritance concepts further in future tutorials on class.

Definitions

abstract data type

AFXWIN

    This is a header for the Microsoft Foundation Classes C++ library. It must be included in all MFC applications.

Ancestor

    An ancestor or forebear is a parent or (recursively) the parent of an ancestor (i.e., a grandparent, great-grandparent, great-great-grandparent, and so forth). Ancestor is "any person/class from whom one/class is descended. In law the person from whom an estate/class has been inherited."

CFrameWnd

    The CFrameWnd class encapsulates the functionality of a Windows single document interface (SDI) frame window. A frame window is a window that frames an application.

CWinApp

    The CWinApp class is the base class from which you derive a Windows application object. An application object provides member functions for initializing your application (and each instance of it) and for running the application.

CStatic

    The CStatic class provides the functionality of a Windows static control. A static control is a control used to display text, to draw frames or lines separating other controls, or to display icons. A static control doesn't accept user input, but it can notify its parent of stylus taps if it's created with SS_NOTIFY style.

DNA (Deoxyribonucleic acid)

    is a molecule that carries most of the genetic instructions used in the development, functioning and reproduction of all known living organisms and many viruses.

event handling

IDE (Integrated development environment)

    is a software application that provides comprehensive facilities that allows you to develop software An IDE usually consists of a source code editor, build automation tools and a debugger.

inheritance

    is the ability to create a class that derives properties from one or more base classes.

initinstance

    Override InitInstance to initialize each new instance of your application running under Windows. Typically, you override InitInstance to construct your main window object and set the CWinThread::m_pMainWnd data member to point to that window.

m_pMainWnd

    Holds a pointer to the application’s main window.

SS_CENTER

    Designates a simple rectangle and displays the given text centered in the rectangle. The text is formatted before it is displayed. Words that would extend past the end of a line are automatically wrapped to the beginning of the next centered line.

Template

    is a unique class or pattern that can be used to build other software code.

WS_BORDER

    Creates a window that has a border.

WS_CHILD

    Creates a child window. Cannot be used with the WS_POPUP style.

WS_VISIBLE

    Creates a window that is initially visible.







HOME] Consulting Design Maintenance Project Testing Training Turnkey Java C++ SQL HTML JavaScript C#

© 2002 - 2016 All Rights Reserved Total Application Works