0% found this document useful (0 votes)
10 views17 pages

OOP Lab - 8

The document is a lab manual for CS-103 (Object Oriented Programming) at the University of Engineering and Technology, Taxila, focusing on the concept of inheritance in programming. It explains the definitions of base and derived classes, the syntax for implementing inheritance in C++, and provides examples of single and multiple inheritance. Additionally, it discusses access specifiers and levels of inheritance, along with practical programming tasks for students to complete.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views17 pages

OOP Lab - 8

The document is a lab manual for CS-103 (Object Oriented Programming) at the University of Engineering and Technology, Taxila, focusing on the concept of inheritance in programming. It explains the definitions of base and derived classes, the syntax for implementing inheritance in C++, and provides examples of single and multiple inheritance. Additionally, it discusses access specifiers and levels of inheritance, along with practical programming tasks for students to complete.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA

DEPARTMENT OF COMPUTER SCIENCE


http://web.uettaxila.edu.pk

CS-103 | Object Oriented Programming (Lab)

LAB Manual 9,10

- Projects / Groups
- Inheritence

Instructor
Muhammad Faheem Saleem

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

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.

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

Syntax:

class <derived_class_name> : <access-specifier> <base_class_name>


{
//body
}
Where
class — keyword to create a new class
derived_class_name — name of the new class, which will inherit the base class
access-specifier — either of private, public or protected. If neither is specified, PRIVATE is
taken as default
base-class-name — name of the base class
Note: A derived class doesn’t inherit access to private data members. However, it does inherit
a full parent object, which contains any private members which that class declares.
When to use ?
Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be the same for all three classes. If we create these
classes avoiding inheritance then we have to write all of these functions in each of the three
classes as shown below figure:

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

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

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;
}
};

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

class Student : private Person {


char course[50];
int fee;
public:
void set_s() {
set_p();
cout << "Enter the Course Name:" << endl;

cin.ignore(); // Clear the input buffer

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;
};

// Sub class inheriting from Base Class(Parent)


class Child : public Parent {
public:
int id_c;

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

};

// main function
int main()
{
Child obj1;

// An object of class child has all data members


// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is: " << obj1.id_c << '\n';
cout << "Parent id is: " << obj1.id_p << '\n';

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’.

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

Example: C++ program to demonstrate protected members

#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;
}

void setColor(string clr) {


color = clr;
}

string getColor() {
return color;
}
};

// derived class
class Dog : public Animal {

public:

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

void setType(string tp) {


type = tp;
}

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;

// Calling members of the base class


dog1.eat();
dog1.sleep();
dog1.setColor("black");

// Calling member of the derived class


dog1.bark();
dog1.setType("mammal");

// Using getColor() of dog1 as argument


// getColor() returns string data
dog1.displayInfo(dog1.getColor());

return 0;
}

Output

I can eat!
I can sleep!

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

I can bark! Woof woof!!


I am a mammal
My color is black

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.

class Dog : public Animal {

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.

// Error: member "Animal::type" is inaccessible


dog1.type = "mammal";

Modes of Inheritance: There are 3 modes of inheritance.

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.

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

// Example : C++ Implementation to show that a derived class


// doesn’t inherit access to private data members.
// However, it does inherit a full parent object.

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
};

class D : private A // 'private' is default for classes


{
// x is private
// y is private
// z is not accessible from D
};

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:

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

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.

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};

OR

class A
{
... .. ...
};

class B: public A
{
... .. ...
};

Example: C++ program to explain Single inheritance

#include<iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle\n";
}
};

// sub class derived from a single base classes


class Car : public Vehicle {

};

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

// 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
{
};

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

class C : public A, public B // C is derived from A and B


{
};
The base classes from which C is derived are listed following the colon in C’s
specification; they are separated by commas.

Example : C++ program to explain multiple inheritance

#include <iostream>
using namespace std;

// first base class


class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};

// second base class


class FourWheeler {
public:
FourWheeler()
{
cout << "This is a 4 wheeler Vehicle\n";
}
};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {
};

// main function
int main()
{
// Creating object of sub class will
// invoke the constructor of base classes.
Car obj;
return 0;}

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

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:

2. Member Functions in Multiple Inheritance


As an example of multiple inheritance, suppose that we need to record the educational
experience of some of the employees in the EMPLOY program. Let’s also suppose that,
perhaps in a different project, we’ve already developed a class called student that models
students with different educational backgrounds. We decide that instead of modifying
the employee class to incorporate educational data, we will add this data by multiple
inheritance from the student class. The student class stores the name of the school or
university last attended and the highest degree received. Both these data items are stored
as strings. Two member functions, getedu() and putedu(), ask the user for this
information and display it. Educational information is not relevant to every class of

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

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

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
DEPARTMENT OF COMPUTER SCIENCE
http://web.uettaxila.edu.pk

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.

Lab Manual: CS-103 (Object Orient Programming) Muhammad Faheem Saleem

You might also like