Home >Backend Development >C++ >new vs. override: When Should You Use Each Method Modifier in Inheritance?
Understand the
and modification character new
override
In object -oriented programming, inherit the method that allows the derived class to reuse and modify the base class. However,
are two different modifiers. They can be used with the inheritance method, and each has a specific purpose. new
override
Situation 1: Use the inheritance method of the
new
When using the modifier, the derived class creates a separate method of the same name as the base method. This actually hides the visibility of base class methods in derivatives. The coding of the base class directly uses the implementation of the base class method, and the coding codes that reference the derived class will use the implementation of the derived class method.
modifier new
On the other hand, The modification of the derivative class is designed to replace it with the base class method with the same signature. This means that when the method is called on the reference of the base class, it will always use the realization of the definition of the derivative class.
override
Key differences
override
Visible:
Hide the base class method, and replace it.
Call and analysis:new
Example: override
new
Example override
new
In this example, the override
modifier in the derived class ensure that when the doit () is called on the Derived class, it will execute the realization of the definition in Derived.doit, regardless of what the type of reference type is used. Essence The above is the detailed content of new vs. override: When Should You Use Each Method Modifier in Inheritance?. For more information, please follow other related articles on the PHP Chinese website!