๐ Date: Feb 17, 2026
๐ง Mood: Lazy Genius (Reusing Code) ๐งฌ
๐ฅ Topic: OOPs Part 5: Inheritance
๐งฌ What is Inheritance?
In real life, you inherit genes from your parents (Height, Eye Color). You don't create them from scratch.
In C++, Inheritance allows a class (Child) to acquire the properties and behaviors of another class (Parent).
⚡ Why use it?
To follow the DRY Principle (Don't Repeat Yourself). Write the common code once in the Parent class, and reuse it in all Child classes.
๐ณ Types of Inheritance
C++ supports 5 types of relationships:
- Single: One Parent → One Child.
- Multilevel: Grandfather → Father → Child.
- Multiple: Two Parents → One Child (Confusing, but C++ allows it).
- Hierarchical: One Parent → Many Children.
- Hybrid: Mix of all.
๐ป The Syntax (Parent & Child)
Let's create a Human class and inherit it into Student.
#include <iostream>
using namespace std;
// 1. PARENT CLASS (Base Class)
class Human {
public:
int height;
int weight;
int age;
void speak() {
cout << "๐ฃ️ Human is Speaking..." << endl;
}
};
// 2. CHILD CLASS (Derived Class)
// Syntax: class Child : mode Parent
class Student : public Human {
public:
int rollNo;
void study() {
cout << "๐ Student is Studying..." << endl;
}
};
int main() {
Student s1;
// Accessing Child's own property
s1.rollNo = 101;
// ⚡ Accessing Parent's property (Inherited)
s1.height = 6;
s1.speak(); // Output: Human is Speaking...
s1.study(); // Output: Student is Studying...
cout << "Student Height: " << s1.height << "ft" << endl;
return 0;
}
๐ก️ The "Protected" Access Modifier
Remember private data cannot be accessed?
If you want the Child class to access Parent's data but keep it hidden from the world, use protected instead of private.
๐ Day 48 Challenge
- Create a class
Vehiclewith a functiondrive(). - Create a child class
CarinheritingVehicle. - Add a property
colorto Car. - In
main(), create aCarobject and call bothdrive()(from parent) and set its color.
Next Up: Day 49 - Polymorphism (One Name, Many Forms).
No comments:
Post a Comment