C++ Inheritance
Inheritance in C++ allows a class (called a derived class or child class) to inherit properties and behaviors (data members and member functions) from another class (called a base class or parent class). It promotes code reuse and establishes a relationship between different classes, reflecting a real-world hierarchy.
Types of Inheritance
- Single Inheritance: One class inherits from one base class.
- Multiple Inheritance: One class inherits from more than one base class.
- Multilevel Inheritance: A class is derived from a class that is also derived from another class.
- Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
- Hybrid Inheritance: A combination of multiple and multilevel inheritance.
Syntax
Here’s an example of single inheritance in C++:
cpp#include
using namespace std;
// Base class
class Animal {
public:
void eat() {
cout << "This animal is eating." << endl;
}
};
// Derived class (inherits from Animal)
class Dog : public Animal {
public:
void bark() {
cout << "The dog is barking." << endl;
}
};
int main() {
Dog dog1;
// Dog can use both its own methods and the inherited methods from Animal
dog1.eat(); // Inherited method
dog1.bark(); // Dog-specific method
return 0;
}
Explanation of the Code
: This class has a method eat(), which is common to all animals.: The Dogclass inherits fromAnimaland can also define its own methods, likebark().
Access Specifiers in Inheritance
When you inherit from a base class, the access specifier (e.g., public, protected, or
private) determines how the base class members are accessible in the derived class:
- Public Inheritance: Public members of the base class remain public in the derived class, and protected members remain protected.
- Protected Inheritance: Public and protected members of the base class become protected in the derived class.
- Private Inheritance: Public and protected members of the base class become private in the derived class.
Example of Protected and Private Inheritance
cppclass Base {
protected:
int x;
public:
void setX(int val) {
x = val;
}
};
// Public inheritance
class DerivedPublic : public Base {
public:
void show() {
cout << "Public inheritance, x = " << x << endl;
}
};
// Private inheritance
class DerivedPrivate : private Base {
public:
void show() {
setX(20); // Can still access through methods
cout << "Private inheritance, x = " << x << endl;
}
};
Types of Inheritance (Further Examples)
- Multiple Inheritance: Inherit from more than one class:
cppclass Animal {
// Base class 1
};
class Mammal {
// Base class 2
};
class Dog : public Animal, public Mammal {
// Derived class
};