Inheritance and polymorphism are powerful tools in C++ that improve code reusability: Inheritance: allows subclasses to inherit features from a base class, eliminating duplicate code. Polymorphism: allows objects to respond to method calls based on type, improving scalability and flexibility. For example, in the animal kingdom, the Cat and Dog classes inherit the eat() method of the Animal class and dynamically call their respective makeSound() methods through polymorphism to achieve code reusability and scalability.
Inheritance and polymorphism in C++: A powerful tool to improve code reusability
What are inheritance and Polymorphism?
Benefits of code reusability
By using inheritance and polymorphism, a high degree of code reusability can be achieved:
Practical Example: The Animal Kingdom
Let’s consider an example from the Animal Kingdom that shows inheritance and polymorphism in action:
Base class Animal:
class Animal { public: void eat() { cout << "Animal is eating." << endl; } };
Subclasses Cat and Dog:
class Cat : public Animal { public: void makeSound() { cout << "Meow!" << endl; } }; class Dog : public Animal { public: void makeSound() { cout << "Woof!" << endl; } };
In the main function, we can use polymorphism to dynamically select Object methods:
int main() { Animal* cat = new Cat(); Animal* dog = new Dog(); cat->eat(); // 调用基类方法 dog->eat(); // 调用基类方法 cat->makeSound(); // 调用子类方法 dog->makeSound(); // 调用子类方法 delete cat; delete dog; return 0; }
In this example, inheritance allows the cat and dog classes to reuse the eat() method. Polymorphism allows us to dynamically call the makeSound() method based on the actual type of the object. This makes the code highly reusable and extensible.
The above is the detailed content of What is the role of inheritance and polymorphism in code reusability in C++?. For more information, please follow other related articles on the PHP Chinese website!