What is Inheritance ? Explain in Details
In : BCA Subject : OOPS and Data StructuresInheritance is one of the core concepts of Object-Oriented Programming (OOP) . It allows a class (called a child or derived class ) to inherit properties and behaviors (like variables and functions) from another class (called a parent or base class ).
Types of Inheritance:
- Single - One class inherits from one parent
- Multiple - One class inherits from multiple parents
- Multilevel - A class inherits from a class that itself inherits from another
- Hierarchical - Multiple classes inherit from one parent
- Hybrid - Combination of two or more types above
Inheritance:
- Allows a class to inherit properties and methods from another class.
- Promotes code reuse , modularity , and organization .
Example :
#include
using namespace std;
// Base class
class Person {
protected:
string name;
public:
void setName(string n) {
name = n;
}
void printName() {
cout << "Name: " << name << endl;
}
};
// Derived class
class Student : public Person {
private:
int rollNo;
public:
void setRoll(int r) {
rollNo = r;
}
void printDetails() {
printName(); // inherited function
cout << "Roll No: " << rollNo << endl;
}
};
int main() {
Student s1;
s1.setName("itprashnavali");
s1.setRoll(101);
s1.printDetails();
return 0;
}