Skip to content

Single inheritance,

๐Ÿ“˜ 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 from Person 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 from Person using the public keyword.
  • Student can access both getDetails() and showDetails() from Person.
  • 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, or private).