Home >Backend Development >C++ >How Do I Properly Invoke Inherited Events in Derived Classes?

How Do I Properly Invoke Inherited Events in Derived Classes?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-28 10:12:11751browse

How Do I Properly Invoke Inherited Events in Derived Classes?

Custom Event Invocation in Inherited Classes

In object-oriented programming, inheritance allows derived classes to inherit properties and behaviors from base classes. However, certain aspects of inherited members may require special handling.

In this case, we have a base class with two events, Loading and Finished, which trigger notifications when specific actions occur. When attempting to raise these events in an inherited class, an error is encountered.

The reason for this error is that events are not simply methods; they are delegates that encapsulate a list of subscribed event handlers. In the inherited class, the compiler expects you to access the event delegate itself, rather than calling it directly.

To address this, we need to create protected methods in the base class that encapsulate event invocation. These methods, named OnLoading and OnFinished, will check if any event handlers are registered and invoke them appropriately.

In the inherited class, we can then call these protected methods to raise the events. By doing so, we ensure that event notifications are propagated correctly to all subscribed handlers. Here's an example:

// Base class
public class BaseClass
{
    public event EventHandler Loading;
    public event EventHandler Finished;

    protected virtual void OnLoading(EventArgs e)
    {
        Loading?.Invoke(this, e);
    }

    protected virtual void OnFinished(EventArgs e)
    {
        Finished?.Invoke(this, e);
    }
}

// Derived class
public class DerivedClass : BaseClass
{
    public void DoSomething()
    {
        ...
        OnLoading(EventArgs.Empty);
        ...
        OnFinished(EventArgs.Empty);
    }
}

By following this approach, we can successfully raise inherited events in derived classes and ensure that subscribed event handlers are notified appropriately.

The above is the detailed content of How Do I Properly Invoke Inherited Events in Derived Classes?. 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