Whithin my sub-class, should I refer to an inherited protected non-virtual method as this.Method()
or base.Method()
?
Using this
would allow me to easily hide the method with a new method of the same name. Should calls to the method explicitly specifiy base
only when it is certain that only the base class' implementation specifically needs to be called?
You cannot override a non-virtual or static method. The overridden base method must be virtual , abstract , or override . An override declaration cannot change the accessibility of the virtual method. Both the override method and the virtual method must have the same access level modifier.
If you don't use virtual functions, you don't understand OOP yet. Because the virtual function is intimately bound with the concept of type, and type is at the core of object-oriented programming, there is no analog to the virtual function in a traditional procedural language.
Omitting the virtual keyword declares a method as non-virtual. Simply speaking, declaring a method as virtual enables overriding, declaring a method as non-virtual disables overriding.
Base classes can't inherit what the child has (such as a new function or variable). Virtual functions are simply functions that can be overridden by the child class if the that child class changes the implementation of the virtual function so that the base virtual function isn't called. A is the base class for B,C,D.
If you're ever going to add a member named Method
in your sub-class and still want to invoke the inherited method, you should use base.Method()
.
Adding members named Method
in more derived classes will not change the meaning of this.Method()
invocation.
Call always using this.Method()
.
If you hide the method, you'll probably want to call the new method instead of the one in the base class. On the other hand, if you make the base class' method virtual, you'll probably want to make your code to call if in a polymorphic way.
It's hard to predict the future, but these scenarios seems more likely to happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With