Inheritance is one of the core features of Object-Oriented Programming. It allows a new class (called derived class) to acquire the properties and behaviors (data members and member functions) of an existing class (called base class).
๐ It promotes code reuse, extensibility, and maintainability.
Syntax:
class DerivedClassName : access_specifier BaseClassName {
// Members of the derived class
};
โ Example: Basic Inheritance
#include <iostream>
using namespace std;
class Animal {
public:
void sound() {
cout << "Animal makes sound" << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Dog barks" << endl;
}
};
int main() {
Dog d;
d.sound(); // Inherited from Animal
d.bark(); // Defined in Dog
return 0;
}
๐ Output:
Animal makes sound
Dog barks