OOP Lab - 8
OOP Lab - 8
- Projects / Groups
- Inheritence
Instructor
Muhammad Faheem Saleem
Topics: Inheritance
a. Inheritance
Inheritance is a way of creating a new class by starting with an existing class and
adding new members. In other words, the capability of a class to derive properties and
characteristics from another class is called Inheritance. Inheritance is one of the most
important features of Object-Oriented Programming. The new class can replace or extend
the functionality of the existing class. The existing class is called the base class and the
new class is called the derived class.
When we say derived class inherits the base class, it means, the derived class inherits all
the properties of the base class, without changing the properties of base class and may add
new features to its own. These new features in the derived class will not affect the base
class. The derived class is the specialized class for the base class.
Sub Class: The class that inherits properties from another class is called Subclass or Derived
Class.
Super Class: The class whose properties are inherited by a subclass is called Base Class or
Superclass.
Syntax:
You can clearly see that the above process results in duplication of the same code 3 times. This
increases the chances of error and data redundancy. To avoid this type of situation, inheritance
is used. If we create a class Vehicle and write these three functions in it and inherit the rest of
the classes from the vehicle class, then we can simply avoid the duplication of data and
increase re-usability. Look at the below diagram in which the three classes are inherited from
vehicle class:
Using inheritance, we have to write the functions only one time instead of three times as we have
inherited the rest of the three classes from the base class (Vehicle).
// Example: define member function without argument within the class
#include<iostream>
using namespace std;
class Person {
int id;
char name[100];
public:
void set_p() {
cout << "Enter the Id:" << endl;
cin >> id;
cin.ignore(); // Clear the input buffer
cout << "Enter the Name:" << endl;
cin.get(name, 100);
}
void display_p() {
cout << endl << id << "\t" << name << endl;
}
};
cin.getline(course, 50);
cout << "Enter the Course Fee:";
cin >> fee;
}
void display_s() {
display_p();
cout << "\t" << course << "\t" << fee << endl;
}
};
int main() {
Student s;
s.set_s();
s.display_s();
return 0;
}
// Example C++ program to demonstrate implementation of inheritance
#include <bits/stdc++.h>
using namespace std;
// Base class
class Parent {
public:
int id_p;
};
};
// main function
int main()
{
Child obj1;
return 0;
}
In the above program, the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public
data members of the class ‘Parent’ will also be inherited by the class ‘Child’.
#include <iostream>
#include <string>
using namespace std;
// base class
class Animal {
private:
string color;
protected:
string type;
public:
void eat() {
cout << "I can eat!" << endl;
}
void sleep() {
cout << "I can sleep!" << endl;
}
string getColor() {
return color;
}
};
// derived class
class Dog : public Animal {
public:
void displayInfo(string c) {
cout << "I am a " << type << endl;
cout << "My color is " << c << endl;
}
void bark() {
cout << "I can bark! Woof woof!!" << endl;
}
};
int main() {
// Create object of the Dog class
Dog dog1;
return 0;
}
Output
I can eat!
I can sleep!
Here, the variable type is protected and is thus accessible from the derived class Dog. We can see
this as we have initialized type in the Dog class using the function setType().
On the other hand, the private variable color cannot be initialized in Dog.
public:
void setColor(string clr) {
// Error: member "Animal::color" is inaccessible
color = clr;
}
};
Also, since the protected keyword hides data, we cannot access type directly from an object
of Dog or Animal class.
Public Mode: If we derive a subclass from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the base class will
become protected in the derived class.
Protected Mode: If we derive a subclass from a Protected base class. Then both public members
and protected members of the base class will become protected in the derived class.
Private Mode: If we derive a subclass from a Private base class. Then both public members and
protected members of the base class will become Private in the derived class.
Note: The private members in the base class cannot be directly accessed in the derived class,
while protected members can be directly accessed. For example, Classes B, C, and D all contain
the variables x, y, and z in the below example. It is just a question of access.
class A {
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A {
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};
The below table summarizes the above three modes and shows the access specifier of the
members of the base class in the subclass when derived in public, protected and private modes:
b. Levels of Inheritance
Classes can be derived from classes that are themselves derived. Here’s a mini-program
that shows the idea:
class A
{ };
class B : public A
{ };
class C : public B
{ };
Here B is derived from A, and C is derived from B. The process can be extended to an
arbitrary number of levels—D could be derived from C, and so on.
Single Inheritance: In single inheritance, a class is allowed to inherit from only one
class. i.e. one subclass is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
OR
class A
{
... .. ...
};
class B: public A
{
... .. ...
};
#include<iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};
};
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes
Car obj;
return 0;
}
Output
This is a Vehicle
Multiple Inheritance
A class can be derived from more than one base class. This is called multiple inheritance.
Figure shows how this looks when a class C is derived from base classes A and B. i.e one
subclass is inherited from more than one base class.
The syntax for multiple inheritance is similar to that for single inheritance. In the
situation shown in Figure, the relationship is expressed like this:
class A // base class A
{
};
class B // base class B
{
};
#include <iostream>
using namespace std;
// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;}
Output
This is a Vehicle
This is a 4 wheeler Vehicle
Class Tasks:
1. As a more concrete example, suppose that we decided to add a special kind of laborer
called a foreman to the EMPLOYEE program. We’ll create a new program,
EMPLOYEE2 that incorporates objects of class foreman. Since a foreman is a kind of
laborer, the foreman class is derived from the laborer class, as shown in Figure:
employee. Let’s suppose, somewhat undemocratically, that we don’t need to record the
educational experience of laborers; it’s only relevant for managers and scientists. We
therefore modify manager and scientist so that they inherit from both the employee and
student classes, as shown in Figure:
Home Tasks:
1. Derive a class called employee2 from the employee class in the EMPLOY program in this
chapter. This new class should add a type double data item called compensation, and also
an enum type called period to indicate whether the employee is paid hourly, weekly, or
monthly. For simplicity you can change the manager, scientist, and laborer classes so they
are derived from employee2 instead of employee. However, note that in many
circumstances it might be more in the spirit of OOP to create a separate base class called
compensation and three new classes manager2, scientist2, and laborer2, and use multiple
inheritance to derive these three classes from the original manager, scientist, and laborer
classes and from compensation. This way none of the original classes needs to be modified.
Write a main() program to test the book and tape classes by creating instances of them,
asking the user to fill in data with getdata(), and then displaying the data with putdata().
2. Start with the publication, book, and tape classes of Exercise 1. Suppose you want to add
the date of publication for both books and tapes. From the publication class, derive a new
class called publication2 that includes this member data. Then change book and tape so
they are derived from publication2 instead of publication. Make all the necessary changes
in member functions so the user can input and output dates along with the other data. For
the dates, you can use the date class from Exercise 5 in Chapter 6, which stores a date as
three ints, for month, day, and year.