Example of inheritance in C++ (part 1)

Written by Hamza on. Posted in C++

After a short break, we now continue our series on C++ object oriented programming. Inheritance in C++ has many real time applications. In this article I will be focusing on just one example where inheritance may be used in a C++ program: the database of a workplace organization. This example of inheritance in C++(part 1) is simple and will make clear to you many of the fine details needed to become a good programmer.

This example is an extremely simplified version of a workplace, in this case an  imaginary organization called CrytpoZone. CryptoZone is an organization that has three different kinds of employees: Scientists, Managers and Technicians. The scientists are further categorized into Security Analysts and Crypto Analysts. It is immediately clear that all of the above, when translated into a C++ program, will be made into classes, as all are separate entities and have different distinct functions in the organization. There must also be a base class which all these classes will be derived from. This class will be the CryptEmployee class.

I have previously mentioned when making relationships using inheritance in C++, we use the ‘is a’ relationship to zone in on an inheritance relationship between two classes. Here, the main class would be called CryptEmployee, and the three basic kinds of employees derived from this class as these all form an ‘is a’ relationship with this class. For example, Manager IS A CryptEmployee. Using the same logic, security analysts and crypto analysts will be derived from the Scientists class.

Let us now look at how to code such a relatively complex problem. Let’s start from the interface, or the .h file. of the CryptEmployee class. This will contain all the data and functionalities that are common to ALL employees.

. class CryptEmployee{

. char*name;
.  int id;
.  int salary;
.  int tax;
.  public:
.  cryptoemployee();                                          //default constructor
.  void enteremployeedata();                         //basic interface for entering employee data
.  void displayemployeedata();                    //basic interface to display employee data

.  //                   getters and setters of the salary field

.  int get_salary();
.  int set_salary();


I will come on to the implementation of these functions later when we have discussed all other classes.

This main class will have three children and one of its children will have a further two children. Every function of a derived class will be available to its parent. This gives our program shape and structure. We will continue this example tomorrow night, and I will be explaining the rest of the classes codes. Stay tuned!

Tags: , , ,

Trackback from your site.

Comments (2)

  • anony


    Please write something about event-driven silulation


    • Raza


      Ok we shall try to do so in future.


Leave a comment