What is Inheritance?
Inheritance is an OOP feature where a new class is created from an existing class.
The existing class is the base class. The new class is the derived class.
class Derived : public Base {
// extra members
};
The derived class can reuse accessible members of the base class and add its own new data or functions.
Why We Use Inheritance
Inheritance is used for:
- Code reuse.
- Representing "is-a" relationships.
- Extending existing classes.
- Avoiding repeated common code.
- Supporting runtime polymorphism when used with virtual functions.
Example relationship:
Animal -> Dog
A dog is an animal, so public inheritance makes sense.
Complete Example
#include <iostream>
#include <string>
using namespace std;
class Animal {
protected:
string name;
public:
Animal(string animalName) : name(animalName) {}
void eat() const {
cout << name << " is eating" << endl;
}
};
class Dog : public Animal {
public:
Dog(string dogName) : Animal(dogName) {}
void bark() const {
cout << name << " is barking" << endl;
}
};
int main() {
Dog dog("Tommy");
dog.eat();
dog.bark();
return 0;
}
Output:
Tommy is eating
Tommy is barking
What Is Inherited?
With public inheritance, the derived class can use:
- Public members of the base class.
- Protected members of the base class.
The derived class cannot directly access:
- Private members of the base class.
Important: private base members still exist inside the derived object. They are just not directly accessible by the derived class.
What Is Not Inherited Directly?
These are not inherited as ordinary usable members:
- Constructors.
- Destructors.
- Assignment operator in the simple beginner sense.
- Private members as directly accessible names.
Constructors and destructors are still called automatically during object creation and destruction.
Inheritance vs Composition
Use inheritance for "is-a".
class Student : public Person { };
Use composition for "has-a".
class Car {
private:
Engine engine;
};
Inheritance is powerful, but wrong inheritance makes code confusing.
Viva Answer
Inheritance is an OOP mechanism where a derived class is created from a base class. It allows the derived class to reuse accessible base-class members and add new features. It should mainly be used for true "is-a" relationships.
Quick Check
- What is a base class?
- What is a derived class?
- Should
Carinherit fromEngine, or should it contain anEngineobject?