Home >Backend Development >C++ >What's the Difference Between `new` and `override` Keywords in Method Inheritance?
In object -oriented programming, inheritance is the core concept, allowing derivatives to expand and modify the behavior of base classes. When defining these classes, developers may need to rewrite or create new implementation. In order to clarify this difference, let's examine the following scenes:
Scene 1: Base class
This grammar declares a virtual method in the base class. The virtual method can be rewritten in the derivative category to provide specific implementation.
<code class="language-c#">public virtual void DoIt();</code>Scene 1: Division class
In the derived method, the use of "New" will create a new and independent method, and its name is the same as the method in the base class. However, this is not considered to be rewritten, and when the base class is called, the behavior of the base class method will not affect the behavior of the base class.
Scene 2: Base class<code class="language-c#">public new void DoIt();</code>
This is a non -futant method and cannot be rewritten in the derived class. The derivatives must use the "NEW" modifier to achieve a new method with the same name. Scene 2: Division class
<code class="language-c#">public void DoIt();</code>
"Override" modifiers indicate that the method in the derivative class is rewriting another method of the same signature in the base class. When calling is called by a base class, the method of rewriting will be executed.
Actual differences
<code class="language-c#">public override void DoIt();</code>
In this example, "derived.doit ()" rewritten "base.doit ()", and when the "B" variable "DOIT ()" method is called from the "B" variable "DERIVED" object, it will be called to call it.
The above is the detailed content of What's the Difference Between `new` and `override` Keywords in Method Inheritance?. For more information, please follow other related articles on the PHP Chinese website!