Inheritance is a feature of object-oriented programming that allows a class to inherit the properties and behaviors of another class. It allows you to create a new class that is a modified version of an existing class, without having to rewrite the code in the new class. This can save a lot of time and effort, as it allows you to reuse code and create a hierarchy of classes that share common characteristics.
Here’s an example of how inheritance works in C++:
// Base class (Parent class)
class Animal {
public:
void makeSound() { cout << "Some animal sound" << endl; }
};
// Derived class (Child class)
class Cat : public Animal {
public:
void makeSound() { cout << "Meow" << endl; }
};
int main() {
Cat cat;
cat.makeSound(); // Output: "Meow"
return 0;
}
In this example, the Cat
class is derived from the Animal
class. This means that it inherits all of the properties and behaviors of the Animal
class, including the makeSound()
method. However, the Cat
class has its own implementation of the makeSound()
method, which overrides the one inherited from the Animal
class. When the makeSound()
method is called on an instance of the Cat
class, the version defined in the Cat
class is used.
There are several types of inheritance in C++, including single inheritance, multiple inheritance, and hierarchical inheritance. Each type has its own set of rules and syntax, and they can be used to create different relationships between classes.