Function rewriting means that a subclass creates a different implementation of a function with the same name as its parent class. It is usually used in the following situations: the subclass has specific requirements that are not covered by the parent class. Subclasses need to modify the behavior of parent class functions. The principle of interface isolation requires that parent class interfaces be decomposed into smaller sub-interfaces.
C Occasions for function rewriting: Matching of subclass requirements and parent class interface
What is function rewriting Write?
Function overriding means that a subclass creates a function with the same name as its parent class but different implementations. Through overriding, a subclass can extend or modify the parent class's behavior to meet its specific needs.
Occasions of function rewriting
Function rewriting is usually used in the following situations:
Practical case
Consider the following parent and subclasses:
class Animal { public: virtual void speak() { cout << "Generic animal sound" << endl; } }; class Dog : public Animal { public: virtual void speak() override { cout << "Woof!" << endl; } };
In the Dog
class , we rewrote the speak()
function. This allows the Dog
object to speak in a "Woof!" manner, while the Animal
object still emits the "Generic animal sound".
Notes
The following are some notes on function rewriting:
override
keyword to explicitly indicate that it is a function override. The above is the detailed content of Occasions for C++ function rewriting: compliance between subclass requirements and parent class interface. For more information, please follow other related articles on the PHP Chinese website!