Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual base members not seeing overrides?

Tags:

c#

inheritance

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(); 
    }
}
like image 468
recursive Avatar asked Aug 31 '10 19:08

recursive


People also ask

Is it mandatory to override virtual method in C#?

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.

How to override a virtual method in C#?

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.

Do you have to override virtual methods c++?

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.

What is override final c++?

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.


1 Answers

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.

like image 73
Fredrik Mörk Avatar answered Oct 02 '22 10:10

Fredrik Mörk