๐ What is Single Inheritance?
Single Inheritance is a type of inheritance in C++ where a single derived class inherits from a single base class.
It allows the derived class to reuse the properties and methods of the base class, promoting code reusability and modularity.
๐ Key Features:
- One base class
- One derived class
- Derived class inherits public and protected members (not private) from the base class
๐ง Real-Life Example:
Imagine:
- Class
Person
has general information like name and age. - Class
Student
inherits fromPerson
and adds student-specific info like roll number.
๐ง Syntax:
class BaseClass {
// base class members
};
class DerivedClass : access-specifier BaseClass {
// derived class members
};
- Common access specifier:
public
(to allow access to base class members in derived class).
๐งช C++ Program: Single Inheritance Example
#include <iostream>
using namespace std;
// Base Class
class Person {
public:
string name;
int age;
void getDetails() {
cout << "Enter name: ";
cin >> name;
cout << "Enter age: ";
cin >> age;
}
void showDetails() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
// Derived Class
class Student : public Person {
public:
int roll;
void getStudentData() {
getDetails(); // Call base class method
cout << "Enter roll number: ";
cin >> roll;
}
void showStudentData() {
showDetails(); // Call base class method
cout << "Roll Number: " << roll << endl;
}
};
int main() {
Student s1;
s1.getStudentData();
cout << "\n--- Student Information ---" << endl;
s1.showStudentData();
return 0;
}
โ Sample Output:
Enter name: Rahul
Enter age: 20
Enter roll number: 101
--- Student Information ---
Name: Rahul, Age: 20
Roll Number: 101
๐ฏ Key Points in the Program:
Student
class inherits fromPerson
using thepublic
keyword.Student
can access bothgetDetails()
andshowDetails()
fromPerson
.- Shows code reuse and hierarchical structure.
๐ Advantages of Single Inheritance:
- Reduces code duplication.
- Easy to understand and maintain.
- Simplifies class design when inheritance is straightforward.
๐ Limitations:
- Only suitable when the design involves one-to-one inheritance.
- Does not support scenarios requiring multiple functionalities from different classes.
๐งพ Summary:
- Single Inheritance is the simplest form of inheritance.
- One derived class inherits from one base class.
- Promotes reusability and structure in OOP.
- Access to base class members is controlled by the access specifier (
public
,protected
, orprivate
).