🧬 C++ Inheritance – Reuse and Extend Like a Pro
Inheritance in C++ is like passing down family traits. 👨👩👧 One class can inherit properties and behaviors from another, letting you reuse code and build on it!
🔍 What Is Inheritance?
Inheritance allows a derived class to use the variables and functions of a base class. This helps you avoid repeating code (yay!) and make things more organized.
📦 Syntax of Inheritance
class Derived : access Base { // additional stuff };
- Base: The parent class
- Derived: The child class
- access: public, protected, or private
🔧 Example: Simple Inheritance
#include <iostream> using namespace std; class Animal { public: void speak() { cout << "Animal speaks!" << endl; } }; class Dog : public Animal { public: void bark() { cout << "Dog barks!" << endl; } }; int main() { Dog myDog; myDog.speak(); // Inherited from Animal myDog.bark(); // Own function return 0; }
🔓 Types of Access Specifiers
When inheriting, you can use:
- public: Keeps public members public
- protected: Keeps public & protected as protected
- private: Everything becomes private in the derived class
📚 Types of Inheritance
- Single: One base, one derived
- Multiple: One derived, many bases
- Multilevel: A inherits B, B inherits C
- Hierarchical: One base, many derived
- Hybrid: A mix of all
🔧 Example: Multilevel Inheritance
#include <iostream> using namespace std; class Living { public: void breathe() { cout << "Breathing..." << endl; } }; class Human : public Living { public: void speak() { cout << "Talking..." << endl; } }; class Student : public Human { public: void study() { cout << "Studying..." << endl; } }; int main() { Student s; s.breathe(); s.speak(); s.study(); return 0; }
🧾 Summary
- Inheritance helps reuse code between classes
- Base class passes its features to the derived class
- Use
: public Base
for clean and clear inheritance - It’s like giving your child your awesome coding skills! 😄