0% found this document useful (0 votes)
5 views26 pages

Topic 7 - Inheritance

Inheritance in C++ allows a class to derive properties and methods from another class, promoting code reusability and reducing redundancy. There are several types of inheritance, including single, multiple, hierarchical, multilevel, and hybrid inheritance, each defining different relationships between classes. Visibility modes (public, protected, private) determine access levels for members of the base class in derived classes.

Uploaded by

rameenahmad69
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)
5 views26 pages

Topic 7 - Inheritance

Inheritance in C++ allows a class to derive properties and methods from another class, promoting code reusability and reducing redundancy. There are several types of inheritance, including single, multiple, hierarchical, multilevel, and hybrid inheritance, each defining different relationships between classes. Visibility modes (public, protected, private) determine access levels for members of the base class in derived classes.

Uploaded by

rameenahmad69
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

Inheritance in C++

The capability of a class to derive properties and methods from another class is called Inheritance.
Inheritance is a feature or a process in which, new classes are created from the existing classes.
The new class created is called “derived class” or “child class” and the existing class is known as
the “base class” or “parent class”. The derived class now is said to be inherited from the base class.

Why and when to use inheritance?


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

Types Of Inheritance:
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multilevel inheritance
5. Hybrid inheritance

Single Inheritance:
In single inheritance, a derived class inherits from only one base class.

Multiple Inheritance:
In multiple inheritance, a derived class inherits from more than one base class.
Multilevel Inheritance:
In multilevel inheritance, a derived class becomes a base class for another derived class.

Hierarchical Inheritance:
In hierarchical inheritance, multiple derived classes inherit from the same base class.

Hybrid Inheritance:
Hybrid inheritance is a combination of multiple inheritance and hierarchical inheritance.
Visibility modes can be classified into three categories:
Public: When the member is declared as public, it is accessible to all the functions of the program.
Private: When the member is declared as private, it is accessible within the class only.
Protected: When the member is declared as protected, it is accessible within its own class as well
as the class immediately derived from it.

Public Mode:
When you derive a class using public inheritance, public members of the base class become public
members of the derived class.
Protected members of the base class become protected members of the derived class.
Private members of the base class remain inaccessible to the derived class.
#include <iostream>
using namespace std;

// Base class
class Base
{
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};

// Derived class using public inheritance


class Derived : public Base {
// publicMember is still public in Derived
// protectedMember is now protected in Derived
// privateMember is not accessible in Derived
public:
void display()
{
cout << "publicMember: " << publicMember << endl;
cout << "protectedMember: " << protectedMember << endl;
// cout << "privateMember: " << privateMember << endl; // Compilation error
}
};

int main()
{
Derived d;
[Link] = 10; // Accessible
// [Link] = 20; // Compilation error: protectedMember is protected in
Derived
// [Link] = 30; // Compilation error: privateMember is not accessible
in Derived
[Link]();
return 0;
}

Protected Mode:
When you derive a class using protected inheritance, both public and protected members of the
base class become protected members of the derived class.
Private members of the base class remain inaccessible to the derived class.
#include <iostream>
using namespace std;

// Base class
class Base
{
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};

// Derived class using protected inheritance


class Derived : protected Base {
// Both publicMember and protectedMember are now protected in Derived
// privateMember is not accessible in Derived
public:
void display()
{
cout << "publicMember: " << publicMember << endl;
cout << "protectedMember: " << protectedMember << endl;
// cout << "privateMember: " << privateMember << endl; // Compilation error
}
};

int main()
{
Derived d;
// [Link] = 10; // Compilation error: publicMember is now protected in
Derived
// [Link] = 20; // Compilation error: protectedMember is protected in
Derived
// [Link] = 30; // Compilation error: privateMember is not accessible
in Derived
[Link]();
return 0;
}

Private Mode:
If we derive a class from a Private base class. Then both public members and protected members
of the base class will become Private in the derived class.
#include <iostream>
using namespace std;

// Base class
class Base
{
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};

// Derived class using private inheritance


class Derived : private Base {
// All members of Base are now private in Derived
public:
void display()
{
cout << "publicMember: " << publicMember << endl;
cout << "protectedMember: " << protectedMember << endl;
// cout << "privateMember: " << privateMember << endl; // Compilation error
}
};

int main()
{
Derived d;
// [Link] = 10; // Compilation error: publicMember is now private in
Derived
// [Link] = 20; // Compilation error: protectedMember is now private
in Derived
// [Link] = 30; // Compilation error: privateMember is not accessible
in Derived
[Link]();
return 0;
}
Inheritance Mode Public, Protected and Private:
Public Mode Inheritance:
To access a protected member of a class in the main function, when we implement public
inheritance, you need to define a public member function in the derived class.
#include <iostream>
using namespace std;

// Base class
class Base
{
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};

// Derived class using public inheritance


class Derived : public Base {
public:
// Function to access protectedMember
int getProtectedMember()
{
return protectedMember;
}

void display()
{
cout << "publicMember: " << publicMember << endl;
cout << "protectedMember: " << protectedMember << endl;
}
};

int main()
{
Derived d;
[Link] = 10; // Accessible
// [Link] = 20; // Compilation error: protectedMember is protected in
Derived
// [Link] = 30; // Compilation error: privateMember is not accessible
in Derived
[Link]();

// Accessing protectedMember using a member function


cout << "Accessing protectedMember : " << [Link]() << endl;

return 0;
}
Protected Mode Inheritance:
To access the Public Member and Protected Member in the main function, when we implement
protected inheritance, you need to define a public member function in the Derived class.
#include <iostream>
using namespace std;

// Base class
class Base
{
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};

// Derived class using protected inheritance


class Derived : protected Base {
public:
// Function to access publicMember
int getPublicMember()
{
return publicMember;
}

// Function to access protectedMember


int getProtectedMember()
{
return protectedMember;
}

void display()
{
cout << "publicMember: " << publicMember << endl;
cout << "protectedMember: " << protectedMember << endl;
}
};

int main()
{
Derived d;

// Accessing publicMember using a member function


cout << "Accessing publicMember : " << [Link]() << endl;

// Accessing protectedMember using a member function


cout << "Accessing protectedMember : " << [Link]() << endl;

return 0;
}
Private Mode Inheritance:
To access the Public Member and Protected Member in the main function when we implement
protected inheritance, you need to define a public member function in the Derived class.
#include <iostream>
using namespace std;

// Base class
class Base
{
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
};

// Derived class using private inheritance


class Derived : private Base {
public:
// Function to access publicMember
int getPublicMember()
{
return publicMember;
}

// Function to access protectedMember


int getProtectedMember()
{
return protectedMember;
}

void display()
{
cout << "publicMember: " << getPublicMember() << endl;
cout << "protectedMember: " << getProtectedMember() << endl;
}
};

int main()
{
Derived d;

// Accessing publicMember using a member function


cout << "Accessing publicMember : " << [Link]() << endl;

// Accessing protectedMember using a member function


cout << "Accessing protectedMember : " << [Link]() << endl;

return 0;
}
Can we get Private Member in the main method?
No, you cannot directly access the Private Member from outside the Base class. The
Private Member is encapsulated within the Base class.
Private members are accessible only within the class that defines them. They cannot
be accessed directly from outside the class, including in the main function or any
other function outside the class scope.
Solution?
To access the private Member from outside the Base class, you can provide public
member functions in the Base class that allow controlled access to this private
member.
// Base class
class Base
{
public:
int publicMember;
protected:
int protectedMember;
private:
int privateMember;
public:
// Public member function to access privateMember
int getPrivateMember()
{
return privateMember = 10;
}
};

// Derived class using private inheritance


class Derived : private Base {
public:
// Function to access privateMember indirectly
int getPrivateMemberFromBase()
{
// Accessing privateMember through the base class function
return getPrivateMember();
}
};

int main()
{
Derived d;

// Accessing privateMember through the derived class


cout << "Accessing privateMember from Derived class: " <<
[Link]() << endl;

return 0;
}
Single Inheritance:
In single inheritance, a derived class inherits from only one base class.

A program to understand the concept of Single inheritance using


a student information (name, age, major) system to elaborate on
public inheritance. Without constructor.
#include <iostream>
#include <string>
using namespace std;

// Base class: Person


class Person
{
protected:
string name;
int age;
public:
void setName(string n)
{
name = n;
}

void setAge(int a)
{
age = a;
}

string getName()
{
return name;
}

int getAge()
{
return age;
}

void display()
{
cout << "Name: " << name << ", Age: " << age << endl;
}
};

// Derived class: Student


class Student : public Person {
private:
string major;
public:
void setMajor(string m)
{
major = m;
}

string getMajor()
{
return major;
}

void displayStudent()
{
display(); // Accessing base class function
cout << "Major: " << major << endl;
}
};

int main()
{
// Creating a Student object
Student s;

// Setting student information using setter methods


[Link]("John Doe");
[Link](20);
[Link]("Computer Science");

// Displaying student information using getter methods


cout << "Student Information:" << endl;
[Link]();

return 0;
}

Output:
Student Information:
Name: John Doe, Age: 20
Major: Computer Science

With constructor.

#include <iostream>
#include <string>
using namespace std;

// Base class: Person


class Person
{
protected:
string name;
int age;
public:
Person(string n, int a)
{
name = n;
age = a;
}

void display()
{
cout << "Name: " << name << ", Age: " << age << endl;
}
};

// Derived class: Student


class Student : public Person {
private:
string major;
public:
Student(string n, int a, string m) : Person(n, a)
{
major = m;
}

void displayStudent()
{
display(); // Accessing base class function
cout << "Major: " << major << endl;
}
};

int main()
{
// Creating a Student object
Student s("John Doe", 20, "Computer Science");

// Displaying student information


cout << "Student Information:" << endl;
[Link]();

return 0;
}

Output:
Student Information:
Name: Ali Raza, Age: 20
Major: Computer Science

A program to understand the concept of Single inheritance using


a student information (name, age, major) system to elaborate on
protected inheritance.
#include <iostream>
#include <string>
using namespace std;

// Base class: Person


class Person
{
protected:
string name;
int age;
public:
// Constructor
Person(string n, int a)
{
name = n;
age = a;
}

// Display function
void display()
{
cout << "Name: " << name << ", Age: " << age << endl;
}
};

// Derived class: Student


class Student : protected Person {
private:
string major;
public:
// Constructor
Student(string n, int a, string m) : Person(n, a)
{
major = m;
}

// Display function
void displayStudent()
{
display(); // Accessing base class function
cout << "Major: " << major << endl;
}
};

int main()
{
// Creating a Student object
Student s("Ali Raza", 20, "Computer Science");

// Displaying student information


cout << "Student Information:" << endl;
[Link]();

return 0;
}

Output:
Student Information:
Name: Ali Raza, Age: 20
Major: Computer Science
A program to understand the concept of Single inheritance using
a student information (name, age, major) system to elaborate on
private inheritance.
#include <iostream>
#include <string>
using namespace std;

// Base class: Person


class Person
{
private:
string name;
int age;
public:
// Constructor
Person(string n, int a)
{
name = n;
age = a;
}

// Display function
void display()
{
cout << "Name: " << name << ", Age: " << age << endl;
}
};

// Derived class: Student


class Student : private Person {
private:
string major;
public:
// Constructor
Student(string n, int a, string m) : Person(n, a)
{
major = m;
}

// Display function
void displayStudent()
{
display(); // Accessing base class function
cout << "Major: " << major << endl;
}
};

int main()
{
// Creating a Student object
Student s("John Doe", 20, "Computer Science");

// Displaying student information


cout << "Student Information:" << endl;
[Link]();
return 0;
}

Output:
Student Information:
Name: Ali Raza, Age: 20
Major: Computer Science
Multiple Inheritance:
In multiple inheritance, a derived class inherits from more than one base class.

A program to understand the concept of Multiple Inheritance using


an employee information system to elaborate on public
inheritance.
#include <iostream>
#include <string>
using namespace std;

// Base class: Person


class Person
{
private:
string name;
int age;
public:
// Constructor
Person(string n, int a)
{
name = n; age = a;
}

// Display function
void display()
{
cout << "Name: " << name << ", Age: " << age << endl;
}
};

// Another base class: Department


class Department
{
private:
string departmentName;
public:
// Constructor
Department(string d)
{
departmentName = d;
}

// Display function
void displayDepartment()
{
cout << "Department: " << departmentName << endl;
}
};

// Derived class: Employee


class Employee : public Person, public Department {
private:
int employeeId;
public:
// Constructor
Employee(string n, int a, string d, int id) : Person(n, a), Department(d)
{ employeeId = id; }

// Display function
void displayEmployee()
{
display(); // Accessing base class function from Person
displayDepartment(); // Accessing base class function from Department
cout << "Employee ID: " << employeeId << endl;
}
};

int main()
{
// Creating an Employee object
Employee e("Ali Raza", 30, "Account", 1001);

// Displaying employee information


cout << "Employee Information:" << endl;
[Link]();

return 0;
}

Output:
Employee Information:
Name: Ali Raza, Age: 30
Department: Account
Employee ID: 1001
Multilevel Inheritance:
In multilevel inheritance, a derived class becomes a base class for another derived class.

A program to understand the concept of Multilevel Inheritance


using an product information system to elaborate on public
inheritance.
#include <iostream>
#include <string>
using namespace std;

// Base class: Category


class Category
{
public:
string categoryName;
// Constructor
Category(string name)
{
categoryName = name;
}
};

// Derived class: SubCategory


class SubCategory : public Category {
public:
string subCategoryName;
// Constructor
SubCategory(string category, string subCategory) : Category(category)
{
subCategoryName = subCategory;
}

// Display function
void displaySubCategory()
{
cout << "Category: " << categoryName << endl;
cout << "Subcategory: " << subCategoryName << endl;
}
};

// Another derived class: Product


class Product : public SubCategory
{
private:
string productName;
double price;
public:
// Constructor
Product(string category, string subCategory, string name, double p)
: SubCategory(category, subCategory)
{
productName = name; price = p;
}

// Display function
void displayProduct()
{
displaySubCategory(); // Accessing base class function from SubCategory
cout << "Product: " << productName << ", Price: $" << price << endl;
}
};

int main()
{
// Creating a Product object
Product laptop("Electronics", "Computers", "HP Probook 657b", 35.5);

// Displaying product information


cout << "Product Information:" << endl;
[Link]();

return 0;
}

Output:
Product Information:
Category: Electronics
Subcategory: Computers
Product: HP Probook 657b, Price: $35.5
Hierarchical Inheritance:
In hierarchical inheritance, multiple derived classes inherit from the same base class.

A program to understand the concept of Hierarchical Inheritance


using an product information system to elaborate on public
inheritance.
#include <iostream>
#include <string>
using namespace std;

// Base class: Product


class Product
{
protected:
string productName;
double price;
public:
// Constructor
Product(string name, double p)
{
productName = name;
price = p;
}

// Display function
void displayProduct()
{
cout << "Product: " << productName << ", Price: $" << price << endl;
}
};

// Derived class: Electronics


class Electronics : public Product {
private:
string brand;
public:
// Constructor
Electronics(string name, double p, string b) : Product(name, p)
{
brand = b;
}
// Display function
void displayElectronics()
{
displayProduct(); // Accessing base class function from Product
cout << "Brand: " << brand << endl;
}
};

// Another derived class: Clothing


class Clothing : public Product
{
private:
string size;
public:
// Constructor
Clothing(string name, double p, string s) : Product(name, p)
{ size = s; }

// Display function
void displayClothing()
{
displayProduct(); // Accessing base class function from Product
cout << "Size: " << size << endl;
}
};

int main()
{
// Creating an Electronics object
Electronics tv("Smart TV", 499.99, "Samsung");

// Displaying electronics information


cout << "Electronics Information:" << endl;
[Link]();

// Creating a Clothing object


Clothing shirt("T-Shirt", 19.99, "Medium");

// Displaying clothing information


cout << "\nClothing Information:" << endl;
[Link]();

return 0;
}
Hybrid Inheritance:
Hybrid inheritance is a combination of multiple inheritance and hierarchical inheritance.

A program to understand the concept of Hybrid Inheritance using


an library information system to elaborate on public inheritance.
#include <iostream>
#include <string>
using namespace std;

// Base class: Book


class Book
{
protected:
string title;
string author;
public:
// Constructor
Book(string t, string a) : title(t), author(a) { }

// Display function
void displayBook()
{
cout << "Title: " << title << ", Author: " << author << endl;
}
};

// Derived class: Borrower


class Borrower : public Book {
protected:
string borrowerName;
int borrowerId;
public:
// Constructor
Borrower(string t, string a, string name, int id) : Book(t, a),
borrowerName(name), borrowerId(id) { }
// Display function
void displayBorrower()
{
displayBook(); // Accessing base class function from Book
cout << "Borrower Name: " << borrowerName << ", Borrower ID: " << borrowerId <<
endl;
}
};

// Another derived class: Librarian


class Librarian : public Book
{
protected:
string librarianName;
int librarianId;
public:
// Constructor
Librarian(string t, string a, string name, int id) : Book(t, a),
librarianName(name), librarianId(id) { }

// Display function
void displayLibrarian()
{
displayBook(); // Accessing base class function from Book
cout << "Librarian Name: " << librarianName << ", Librarian ID: " << librarianId
<< endl;
}
};

// Derived class: Library


class Library : public Borrower, public Librarian
{
public:
// Constructor
Library(string bTitle, string bAuthor, int bId, string lTitle, string lAuthor,
int lId) : Borrower(bTitle, bAuthor, "Dummy Name", bId), Librarian(lTitle, lAuthor,
"Dummy Name", lId) { }

// Display function for library


void displayLibrary()
{
displayBorrower(); // Accessing base class function from Borrower
displayLibrarian(); // Accessing base class function from Librarian
}
};
int main()
{
// Creating a Library object
Library library("C++ Fundamentals", "Hassan", 1234, "Ali Raza", "Umer", 5678);

// Displaying library information


cout << "Library Information:" << endl;
[Link]();

return 0;
}

You might also like