-1

When I override a virtual function, I've always assumed the override method would be called only if an object is of that child class type (and not the base type). The following statements in this answer suggest the override will always be called, even if the object is of base type:

Difference between new and override

Even if the method is called on a reference to the base class it will use the implementation overriding it.

The method is overridden and will be invoked regardless of whether the object is cast as the child or parent class.

So I made this setup:

public class Test
{
    public virtual void DoSomething()
    {
        Console.WriteLine("Base called");
    }
}

public class TestChild : Test
{
    public override void DoSomething()
    {
        Console.WriteLine("Child called");
    }
}

class Program
{
    static void Main(string[] args)
    {
        var test = new Test();
        test.DoSomething();
    }
}

Which results in the parent (Test) method being called, not the override. So when those statements say the override will be called, even if the object is cast as child or parent, what exactly do they mean?

Do these statements not include if the object is instantiated as the parent type? (rather than cast)

FBryant87
  • 4,273
  • 2
  • 44
  • 72
  • 1
    You´re mixing "on a reference to the base class" with "an instance of the class". You can of course store an instance of your *derived * class within a *reference* of your *base*-class. On the other side when you have an *instance* of your base-class it surely will call the *base*-method as well. – MakePeaceGreatAgain Sep 20 '17 at 13:35
  • The question that you yourself linked provided *numerous* code examples to demonstrate the points that were being made, so you can see that yours is quite different from those. – Servy Sep 20 '17 at 13:36
  • The explanation has in mind a different program: `Test test = new TestChild(); test.DoSomething();` The type of `test` variable known to the compiler is `Test`, not `TestChild`, but `DoSomething` of `TestChild` is being called. – Sergey Kalinichenko Sep 20 '17 at 13:38

1 Answers1

1

You´re mixing "on a reference to the base class" with "an instance of the class". You can of course store an instance of your derived class within a reference of your base-class.

Test t = new TestChild();

Here t is a reference of type Test, but the actual instance is of type TestChild. When calling any virtual member here the override within TestChild will be executed.

On the other side when you have an instance of your base-class it surely will call the base-method as well:

Test t = new Test();
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111