INHERITANCE IN C++ (Simple Explanation)
What is Inheritance?
--------------------
Inheritance means one class (child) can use the properties and functions of another class (parent).
It helps in code reuse and shows relationship between classes like "is-a".
Real-Life Example:
------------------
Animal -> Base class (parent)
Dog -> Derived class (child)
Dog is an Animal, so it inherits basic things like eat(), sleep().
Basic Syntax in C++:
---------------------
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
};
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
}
};
Types of Inheritance in C++:
----------------------------
1. Single - One base -> One derived (Dog from Animal)
2. Multilevel - Derived becomes base again (Puppy from Dog from Animal)
3. Multiple - One class, multiple bases (Child from Mother, Father)
4. Hierarchical - Multiple classes from one base (Dog, Cat from Animal)
5. Hybrid - Mix of above types
Examples:
---------
1. Single Inheritance:
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
};
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
};
2. Multilevel Inheritance:
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
};
class Dog : public Animal {
public:
void bark() {
cout << "Barking..." << endl;
};
class Puppy : public Dog {
public:
void weep() {
cout << "Weeping..." << endl;
};
3. Multiple Inheritance:
class Father {
public:
void height() {
cout << "Tall height" << endl;
};
class Mother {
public:
void eyes() {
cout << "Brown eyes" << endl;
};
class Child : public Father, public Mother {
public:
void skinTone() {
cout << "Fair skin tone" << endl;
};
Benefits of Inheritance:
------------------------
- Code Reuse
- Reduces Redundancy
- Easy to manage code
- Logical structure like real life