Inheritance is a fundamental concept in object-oriented programming (OOP) languages like C++. It allows a class to inherit properties (data members) and behaviors (member functions) from another class, known as the base class or parent class. The class that inherits from the base class is called the derived class or child class.
With inheritance, the derived class automatically acquires all the public and protected members of the base class, allowing the derived class to reuse and extend the functionality of the base class. This promotes code reusability and helps in building complex software systems.
In C++, there are different types of inheritance, including:
- Single Inheritance: A derived class inherits from a single base class.
- Multiple Inheritance: A derived class inherits from multiple base classes.
- Multilevel Inheritance: A derived class is derived from another derived class.
- Hierarchical Inheritance: Multiple derived classes are derived from a single base class.
- Hybrid Inheritance: A combination of multiple inheritance and multilevel inheritance.
Inheritance is achieved using the class keyword followed by the name of the derived class, a colon, and the access specifier (public, protected, or private) indicating the inheritance type. The base class members can be accessed within the derived class using the scope resolution operator (::).
By utilizing inheritance, C++ programmers can create well-structured, modular code and take advantage of the powerful object-oriented features provided by the language.
Example:
class Shape {
public:
void setColor(string color) {
this->color = color;
}
void draw() {
cout << "Drawing a shape." << endl;
}
private:
string color;
};
class Circle : public Shape {
public:
void draw() {
cout << "Drawing a circle." << endl;
}
};
int main() {
Circle circle;
circle.setColor("Red");
circle.draw();
return 0;
}
In this example, Circle is a derived class that inherits from the Shape base class. The derived class overrides the draw function to provide a specialized implementation for circles.