I always thought base.Something
was equivalent to ((Parent)this).Something
, but apparently that's not the case. I thought that overriding methods eliminated the possibility of the original virtual method being called.
Why is the third output different?
void Main() {
Child child = new Child();
child.Method(); //output "Child here!"
((Parent)child).Method(); //output "Child here!"
child.BaseMethod(); //output "Parent here!"
}
class Parent {
public virtual void Method() {
Console.WriteLine("Parent here!");
}
}
class Child : Parent {
public override void Method() {
Console.WriteLine ("Child here!");
}
public void BaseMethod() {
base.Method();
}
}
When the method is declared as virtual in a base class, and the same definition exists in a derived class, there is no need for override, but a different definition will only work if the method is overridden in the derived class. Two important rules: By default, methods are non-virtual, and they cannot be overridden.
A virtual method is first created in a base class and then it is overridden in the derived class. A virtual method can be created in the base class by using the “virtual” keyword and the same method can be overridden in the derived class by using the “override” keyword.
They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.
override (C++11) final (C++11) [edit] Specifies that a virtual function cannot be overridden in a derived class or that a class cannot be derived from.
Because in BaseMethod
you explicitly call the method in the base class, by using the base
keyword. There is a difference between calling Method()
and base.Method()
within the class.
In the documentation for the base
keyword, it says (amongst other things) that it can be used to Call a method on the base class that has been overridden by another method.
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