Home >Backend Development >C++ >new vs. override: When Should You Use Each Method Modifier in Inheritance?

new vs. override: When Should You Use Each Method Modifier in Inheritance?

Susan Sarandon
Susan SarandonOriginal
2025-01-28 11:51:09812browse

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,

and

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

modifier

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.

Situation 2: Use the inheritance method of the

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:
  • Always call the derived class method, and call the final definition implementation, even if the base class reference access is the same. new Example: override
  • It can be used to create a completely different version of the method, and
  • is used to expand or modify the base method. new Example override
  • Consider the following base classes and derivatives: 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn