Home >Backend Development >C++ >What Does the `new` Keyword Mean in a Method Signature?

What Does the `new` Keyword Mean in a Method Signature?

Susan Sarandon
Susan SarandonOriginal
2025-01-05 07:55:41790browse

What Does the `new` Keyword Mean in a Method Signature?

New Keyword in Method Signature

Question: What does the new keyword signify in a method signature?

Answer: In a method signature, the new keyword indicates that the method is a new method in the derived class that hides the base class implementation of a method. It is different from the override keyword, which can only be used to override virtual methods declared in the base class.

Example:

Consider the following base class:

public class Base
{
    public void BaseMethod() {}
}

Now, let's create a derived class that overrides the BaseMethod method using the override keyword:

public class Derived : Base
{
    public override void BaseMethod() {}
}

In this example, the override keyword tells the compiler that the BaseMethod method in the derived class is overriding the base class implementation.

However, let's now create a different derived class and use the new keyword in the method signature:

public class AnotherDerived : Base
{
    public new void BaseMethod() {}
}

In the above example, the new keyword is used because the BaseMethod method in the derived class is not overriding the base class implementation. Instead, it is creating a new method with the same name as the base class method.

Key Differences between new and override:

  • Overridable methods: The override keyword can only be used to override virtual methods in the base class. The new keyword can hide both virtual and non-virtual methods.
  • Visibility: Overridden methods must have the same or a more derived visibility than the base class method. New methods can have any visibility.
  • Invocation: If a method with the same name is called from the base class reference, the base class implementation will be invoked for overridden methods. However, for new methods, the derived class implementation will be invoked.

The above is the detailed content of What Does the `new` Keyword Mean in a Method Signature?. 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