Q4. Demonstrate the Use of Inheritance
Question:
Write program(s) to demonstrate the use of inheritance.
My Approach
Inheritance C++ ka ek powerful concept hai jaha ek class (child/derived) doosri class (parent/base) ke properties aur methods ko inherit karti hai.
Ye reusability provide karta hai aur real-world modeling ke liye best hai.
Maine is example ke liye ek real-world Student and Result System banaya hai:
- Base Class:
Person→ har person kanameaurage. - Derived Class 1:
Student→Personse inherit karkerollNumberadd karta hai. - Derived Class 2:
Result→Studentse inherit karke marks aur percentage calculate karta hai.
Program Code
File Name: inheritance_demo.cpp
#include <iostream>
using namespace std;
// Base Class
class Person {
protected:
string name;
int age;
public:
Person(string n, int a) {
name = n;
age = a;
}
void displayPerson() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
}
};
// Derived Class 1
class Student : public Person {
protected:
int rollNumber;
public:
Student(string n, int a, int r) : Person(n, a) {
rollNumber = r;
}
void displayStudent() {
displayPerson();
cout << "Roll Number: " << rollNumber << endl;
}
};
// Derived Class 2
class Result : public Student {
private:
float marks1, marks2, marks3;
public:
Result(string n, int a, int r, float m1, float m2, float m3)
: Student(n, a, r) {
marks1 = m1;
marks2 = m2;
marks3 = m3;
}
void displayResult() {
displayStudent();
float total = marks1 + marks2 + marks3;
float percentage = total / 3;
cout << "Marks: " << marks1 << ", " << marks2 << ", " << marks3 << endl;
cout << "Total: " << total << endl;
cout << "Percentage: " << percentage << "%" << endl;
}
};
int main() {
Result r("Intesab Ansari", 23, 101, 78.5, 82.0, 90.0);
cout << "=== Student Result Information ===" << endl;
r.displayResult();
return 0;
}Sample Input / Output
Output:
=== Student Result Information ===
Name: Intesab Ansari
Age: 23
Roll Number: 101
Marks: 78.5, 82, 90
Total: 250.5
Percentage: 83.5%Explanation
Person→ Base class with common details (name,age).Student→ Derived fromPerson, addsrollNumber.Result→ Derived fromStudent, adds marks and percentage calculation.- Example me multi-level inheritance ka use hua hai.
Real Time Relevance
- Education system me Person → Student → Result ek perfect real-world case hai.
- Inheritance ka use har jagah hota hai jaha hierarchy design karni hoti hai, jaise Bank System (Account → Savings/Current), Company (Employee → Manager/Developer), etc.
Conclusion
Is program se inheritance ka real use samajh aata hai. Code reusability aur hierarchy design ke liye ye ek must-know concept hai.
Submitted by:
Intesab Ansari
MCA Student, NMU University
Portfolio: intesab.live
Last updated on