Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this. vs base. for inherited protected non-virtual methods?

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?

like image 959
Monstieur Avatar asked May 02 '13 06:05

Monstieur


People also ask

Can you override non-virtual methods?

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.

What happens if we don't use virtual function in inheritance?

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.

What is non-virtual method?

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.

Can virtual methods be inherited?

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.


2 Answers

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.

like image 135
Zakharia Stanley Avatar answered Nov 10 '22 20:11

Zakharia Stanley


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.

like image 38
Doug Avatar answered Nov 10 '22 22:11

Doug