Inheritance in C++ (OOP)
What is Inheritance?
Inheritance is a mechanism in C++ where a new class (derived) is created from an existing class (base). It
promotes code reuse and is a key feature of OOP.
Syntax
class Base {
// base members
};
class Derived : access_specifier Base {
// derived members
};
Types of Inheritance
1. Single Inheritance -> A -> B
2. Multilevel Inheritance -> A -> B -> C
3. Multiple Inheritance -> A + B -> C
4. Hierarchical Inheritance -> A -> B, A -> C
5. Hybrid Inheritance -> Mix of above types
Access Specifiers
| Inheritance | Public Members | Protected Members | Private Members |
|-------------|----------------|-------------------|-----------------|
| public | public | protected | not inherited |
| protected | protected | protected | not inherited |
| private | private | private | not inherited |
Example: Single Inheritance
Inheritance in C++ (OOP)
class Parent {
public:
void show() {
cout << "I am Parent" << endl;
};
class Child : public Parent {
public:
void greet() {
cout << "Hello from Child" << endl;
};
Output
I am Parent
Hello from Child
Benefits of Inheritance
- Code Reusability
- Logical structure
- Easier maintenance
- Enables polymorphism