Home > Backend Development > C++ > How to Call a Base Class Method Directly, Bypassing Intermediate Overrides?

How to Call a Base Class Method Directly, Bypassing Intermediate Overrides?

Patricia Arquette
Release: 2025-01-01 12:14:10
Original
983 people have browsed it

How to Call a Base Class Method Directly, Bypassing Intermediate Overrides?

Calling Base's Method Directly

In OOP, accessing base class methods within derived classes is essential for method overriding. However, the question arises: "How can we call the base's base method, bypassing any intermediate overrides?"

To avoid the undesired call to Derived.Say() in the SpecialDerived class, the original source code cannot be modified. However, a workaround exists. By introducing a new method, CustomSay(), in the Derived class and overriding it in SpecialDerived, we can redirect the default behavior while preserving the existing Say() method.

Here's the modified code:

// Cannot change source code
class Derived : Base
{
    public override void Say()
    {
        CustomSay();

        base.Say();
    }

    protected virtual void CustomSay()
    {
        Console.WriteLine("Called from Derived.");
    }
}

class SpecialDerived : Derived
{
    protected override void CustomSay()
    {
        Console.WriteLine("Called from Special Derived.");
    }
}
Copy after login

Now, when calling sd.Say(), the result will be:

Called from Special Derived.
Called from Base.
Copy after login

The use of a new method CustomSay() allows for customization without modifying the overridden Say() method. However, it's generally discouraged to access base methods beyond the first level due to its potential for confusion and maintenance issues.

The above is the detailed content of How to Call a Base Class Method Directly, Bypassing Intermediate Overrides?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template