0% found this document useful (0 votes)
14 views11 pages

C++ Inheritance Program Examples

The document presents three C++ programs demonstrating different types of inheritance: Multi-Level Inheritance for calculating student percentages, Multiple Inheritance for managing employee information, and Hybrid Inheritance representing a family hierarchy. Each program includes a detailed algorithm, code implementation, and example outputs. The programs effectively illustrate the concepts of inheritance in C++.

Uploaded by

v12926716
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)
14 views11 pages

C++ Inheritance Program Examples

The document presents three C++ programs demonstrating different types of inheritance: Multi-Level Inheritance for calculating student percentages, Multiple Inheritance for managing employee information, and Hybrid Inheritance representing a family hierarchy. Each program includes a detailed algorithm, code implementation, and example outputs. The programs effectively illustrate the concepts of inheritance in C++.

Uploaded by

v12926716
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

Ex . No.

6 Programs using types of inheritance

Program 1: Multi-Level Inheritance for Student Percentage


Calculation
Write a C++ program to calculate the percentage of a student using
multi-level inheritance. Accept the marks of three subjects in base
class. A class will derive from the above mentioned class which
includes a function to find the total marks obtained and another
class derived from this class which calculates and displays the
percentage of student.
Aim:
To create a C++ program using multi-level inheritance to calculate the
percentage of a student. The base class stores marks of three subjects, the
intermediate class calculates total marks, and the derived class computes and
displays the percentage.

Algorithm:
Step 1: Start
Step 2: Create a base class Student with three subject marks as data
members.
Step 3: Create a derived class Marks that inherits from Student and
includes a function to calculate total marks.
Step 4: Create another derived class Result (from Marks) to compute and
display the percentage.
Step 5: Accept user input for marks, compute total and percentage, and
display the result.
Step 6: Stop

Program :
#include <iostream>
using namespace std;
// Base Class: Student (Stores marks of 3 subjects)
class Student {
protected:
float mark1, mark2, mark3;

public:
void getMarks() {
cout << "Enter marks for 3 subjects: ";
cin >> mark1 >> mark2 >> mark3;
}
};

// Derived Class: Marks (Calculates total marks)


class Marks : public Student {
protected:
float total;

public:
void calculateTotal() {
total = mark1 + mark2 + mark3;
}
};

// Derived Class: Result (Calculates and displays percentage)


class Result : public Marks {
public:
void displayPercentage() {
float percentage = (total / 300) * 100;
cout << "Total Marks: " << total << endl;
cout << "Percentage: " << percentage << "%" << endl;
}
};

// Main function
int main() {
Result student;
[Link]();
[Link]();
[Link]();
return 0;
}

Output :
Enter marks for 3 subjects: 78 85 90
Total Marks: 253
Percentage: 84.33%
Program 2: Multiple Inheritance with Employee Information
Write a C++ program to implement the following and give a
brief description about the identified inheritance:

Aim:
To implement multiple inheritance in C++ where an Employee
class derives from BasicInfo and DepartmentInfo to store and display employee
details.

Algorithm:
Step 1: Start
Step 2: Create a base class BasicInfo with attributes for name and age
and a function to accept and display them.
Step 3: Create another base class DepartmentInfo with attributes for
department and designation and a function to accept and display them.
Step 4: Create a derived class Employee that inherits from both BasicInfo
and DepartmentInfo.
Step 5: The Employee class will have a function to display all employee
details.
Step 6: In the main function, create an object of Employee, take input,
and display the details.
Step 7: Stop
Program :
#include <iostream>
using namespace std;

// Base Class: BasicInfo


class BasicInfo {
protected:
string name;
int age;

public:
void getBasicInfo() {
cout << "Enter Employee Name: ";
cin >> name;
cout << "Enter Employee Age: ";
cin >> age;
}

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

// Base Class: DepartmentInfo


class DepartmentInfo {
protected:
string department, designation;

public:
void getDepartmentInfo() {
cout << "Enter Department: ";
cin >> department;
cout << "Enter Designation: ";
cin >> designation;
}

void displayDepartmentInfo() {
cout << "Department: " << department << endl;
cout << "Designation: " << designation << endl;
}
};

// Derived Class: Employee (inherits from BasicInfo and DepartmentInfo)


class Employee : public BasicInfo, public DepartmentInfo {
public:
void displayEmployeeDetails() {
cout << "\n--- Employee Details ---\n";
displayBasicInfo();
displayDepartmentInfo();
}
};
// Main function
int main() {
Employee emp;
[Link]();
[Link]();
[Link]();
return 0;
}

Output :
Enter Employee Name: John
Enter Employee Age: 30
Enter Department: IT
Enter Designation: Manager

--- Employee Details ---


Name: John
Age: 30
Department: IT
Designation: Manager
Program 3: Hybrid Inheritance with Grandfather, Father, Mother,
and Son Classes
Write a c++ program for the following scenario - Create four
classes: grandfather, father, mother, and son to achieve the
combination of multilevel and hierarchical inheritance (as hybrid
inheritance). Hint: create functions like house(), land(), gold(), car()
in the classes and object for derived class son and access those
functions.
Aim:
To implement hybrid inheritance in C++ with classes Grandfather,
Father, Mother, and Son, demonstrating multiple and multilevel inheritance.

Algorithm:
Step 1: Start
Step 2: Create a base class Grandfather with a function house().
Step 3: Create a derived class Father inheriting from Grandfather, with
an additional function land().
Step 4: Create another class Mother with a function gold().
Step 5: Create a derived class Son that inherits from both Father and
Mother, adding a function car().
Step 6: Create an object of Son and call all functions.
Step 7: Stop

Program:
#include <iostream>
using namespace std;

// Base Class: Grandfather


class Grandfather {
public:
void house() {
cout << "Grandfather owns a house." << endl;
}
};

// Derived Class: Father (inherits from Grandfather)


class Father : public Grandfather {
public:
void land() {
cout << "Father owns agricultural land." << endl;
}
};

// Another Base Class: Mother


class Mother {
public:
void gold() {
cout << "Mother has gold jewelry." << endl;
}
};

// Derived Class: Son (inherits from Father and Mother - Hybrid Inheritance)
class Son : public Father, public Mother {
public:
void car() {
cout << "Son owns a sports car." << endl;
}
};

// Main function
int main() {
Son obj;
[Link]();
[Link]();
[Link]();
[Link]();
return 0;
}

Output:
Grandfather owns a house.
Father owns agricultural land.
Mother has gold jewelry.
Son owns a sports car.
[Link] Particulars Max Marks
marks Obtained
1 Inference 10
2 presentation 3
3 On-time submission 2

TOTAL : 15

Result :
The above three C++ programs successfully demonstrate different types of
inheritance. Program 1 implements Multi-Level Inheritance, where the Result
class inherits from Marks, which in turn inherits from Student, to calculate the
total marks and percentage of a student. Program 2 demonstrates Hybrid
Inheritance, where the Son class inherits from both Father (who inherits from
Grandfather) and Mother, representing a family hierarchy and asset
ownership. Program 3 showcases Multiple Inheritance, where the Employee
class inherits from both BasicInfo and DepartmentInfo to manage and display
employee details. These programs effectively validate the implementation of
different inheritance types in C++.

Common questions

Powered by AI

Encapsulation in C++ is the practice of bundling data and methods that operate on the data within a class, with access restrictions using access specifiers. In the given programs, encapsulation is employed by using 'protected' and 'public' access specifiers, where 'protected' allows derived classes to access inherited class members but restricts them from external access. This encapsulation aids in maintaining control over data and provides a clear interface for class interaction, particularly beneficial in the hierarchical and multiple inheritance contexts to prevent unauthorized access or misuse of internal data .

Each type of inheritance impacts C++ program design differently: Multi-level inheritance, as shown in the student percentage calculation, involves a linear parent-child relationship benefiting code reuse and clarity but risks deep hierarchy complexities. Multiple inheritance, seen in the employee example, offers versatility and integration of diverse functionalities but can lead to ambiguity without careful design. Hybrid inheritance, demonstrated in the asset ownership example, provides a rich framework for mimicking complex real-world relationships but increases design complexity and requires strategic management to prevent issues like the diamond problem and method ambiguities. Each type shapes both the modularity and the sophistication of the program structure, requiring careful balancing of design and functionality needs .

Inheritance in both examples enhances reusability by allowing derived classes to use functions and attributes of base classes without rewriting code, therefore facilitating code reusability. In the student percentage example, different classes handle distinct functions like input, total calculation, and percentage display. Similarly, in the employee example, basic and department information functions are reused in the 'Employee' class, enhancing maintainability by reducing redundancy. Maintainability is further improved by localizing changes to base classes without affecting derived classes, ensuring easier updates and less error-prone modifications .

To manage complexity in hybrid inheritance, several strategies can be employed: 1) Use of clear and consistent naming conventions to avoid method ambiguity across different parent classes. 2) Implement abstract classes and interfaces to define common functions, which can be overridden in derived classes. 3) Explicit use of scope resolution operators to manage ambiguities and ensure clarity on method calls. 4) Proper documentation and use of design patterns like composition over inheritance where appropriate to reduce tight coupling. These strategies help clarify relationships and responsibilities within the complex inheritance hierarchy .

Multi-level inheritance in C++ allows a class to inherit from a derived class, thus creating a chain of inheritance. In the provided program, a base class 'Student' stores marks for three subjects, an intermediate class 'Marks' calculates the total marks by inheriting from 'Student', and a final derived class 'Result' calculates and displays the percentage by inheriting from 'Marks'. This structured approach facilitates segregating responsibilities across different classes, making the code modular and easy to manage .

Multiple inheritance allows a class to inherit features from more than one base class. In the provided program, the 'Employee' class is derived from two base classes, 'BasicInfo' and 'DepartmentInfo'. This setup allows 'Employee' to inherit and utilize attributes and functions from both parent classes, thus efficiently managing and displaying employee details by combining personal and professional information .

Hybrid inheritance offers the advantage of combining multiple and hierarchical inheritance, thus allowing more complex relationships and architectures reflective of real-world entities. In the given programs, hybrid inheritance enables the 'Son' class to inherit attributes from both the 'Father' class (which also inherits from 'Grandfather') and 'Mother'. This enables modeling complex relationships that cannot be effectively captured using single or purely multilevel inheritance, offering flexibility to incorporate traits from different lineages within a unified structure .

One major challenge in implementing multiple inheritance in C++ is the potential for ambiguity, particularly when methods or attributes in base classes have the same name. This can occur in the Employee program if both 'BasicInfo' and 'DepartmentInfo' classes had similarly named functions without distinct scopes. If not managed properly with explicit scope resolution, it can lead to errors. Additionally, there's complexity and maintenance challenges due to the increased coupling between multiple base classes .

Segregating functions across different derived classes in multi-level inheritance is important to promote modularity and maintainability. By separating responsibilities—such as input of marks, calculation of total marks, and computation of percentage—into distinct classes, each class focuses on a single responsibility, which simplifies the code structure and makes it easier to update or debug. This modular design enhances readability, reduces logical dependencies, and enables easier future extensions or modifications without affecting the entire codebase .

The hybrid inheritance program mimics a real-world family hierarchy by combining multilevel and multiple inheritance. The 'Son' class inherits from both 'Father' and 'Mother', where 'Father' himself inherits from 'Grandfather'. This setup creates a multilevel pattern involving father-grandfather relationships and a multiple inheritance pattern via mother-son, illustrating ownership of assets across generations like house, land, gold jewelry, and car, reflecting a realistic familial structure .

You might also like