Inheritance in C++
Inheritance is a fundamental feature of object-oriented programming (OOP) that allows you to create new classes (derived classes) based on existing classes (base classes). In C++, inheritance enables the derived class to inherit the properties (data members and member functions) of the base class, promoting code reuse and facilitating the creation of hierarchical relationships between classes.
To implement inheritance in C++, you use the class keyword and the colon : followed by the access specifier (public, protected, or private) to specify the type of inheritance. There are three types of inheritance relationships:
Single Inheritance
Single inheritance involves creating a derived class that inherits from a single base class. The derived class inherits the members of the base class as if they were its own.
class Base {
public:
void baseMethod() {
// Implementation
}
};
class Derived : public Base {
// Derived class inherits baseMethod() from Base
};
Multiple Inheritance
Multiple inheritance allows a derived class to inherit from multiple base classes. The derived class will have access to the members of all the base classes.
class Base1 {
public:
void base1Method() {
// Implementation
}
};
class Base2 {
public:
void base2Method() {
// Implementation
}
};
class Derived : public Base1, public Base2 {
// Derived class inherits base1Method() from Base1
// and base2Method() from Base2
};
Multilevel Inheritance
Multilevel inheritance involves creating a derived class from another derived class. This creates a hierarchy of classes, with each derived class inheriting from its immediate base class.
class Base {
public:
void baseMethod() {
// Implementation
}
};
class Derived1 : public Base {
// Derived1 class inherits baseMethod() from Base
};
class Derived2 : public Derived1 {
// Derived2 class inherits baseMethod() from Base through Derived1
};
In addition to inheriting the properties of the base class, derived classes can also extend or override the behavior of the base class by providing their own member functions and variables. This allows for specialization and customization of the derived classes.
Inheritance provides a powerful mechanism for code reuse, encapsulation, and creating class hierarchies that model real-world relationships. It is an essential concept in object-oriented programming and enables the creation of complex and flexible systems in C++.