0

What happens when a parent variable type stores a child object and invokes a method that was overridden by the child class?

Does the parent version of the method execute or does the child version of the method execute?

public class testa
{
    public virtual void display()
    {
        System.Diagnostics.Debug.WriteLine('a');
    }
}

public class testb : testa
{
    public override void display()
    {
        System.Diagnostics.Debug.WriteLine('b');
    }
}

then call somewhere

testa b = new testb();
b.display();

Through running this test on my own I found that it says "b", I would still like a formal answer though to fully understand what is happening.

Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
Thomas
  • 6,032
  • 6
  • 41
  • 79
  • I'm unsure if you mean a simple inheritance where you hold a parent who was instantiated to a child, or something more interesting. If it's the second case, add some code or explain yourself better. If it's the first - read this http://en.wikipedia.org/wiki/Virtual_method_table – asafrob Jul 21 '13 at 05:43
  • @asafrob i added code, i'm not sure if this is what you thought it was or not. – Thomas Jul 21 '13 at 06:24

2 Answers2

2

You are referring to Runtime polymorphism. When a virtual method is called on an object, then the most derived version of the method gets called always.

Like in your case, you are calling display (virtual) method which is overriden in testb class. Hence, it gets called to display b.

testa b = new testb();
b.display();

But however, if you are using method hiding using new keyword -

public class testa
{
    public void display()
    {
        System.Diagnostics.Debug.WriteLine('a');
    }
}

public class testb : testa
{
    public new void display()
    {
        System.Diagnostics.Debug.WriteLine('b');
    }
}

And you run this code -

testa b = new testb();
b.display();

You will see a gets print because base class method gets called as its no more virtual.

Refer to the link Overriding VS Method Hiding for more detailed explanation if its not clear yet.

Community
  • 1
  • 1
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
1

When you create a class that contains a virtual function you get something that is called a virtual table (or vtable) The vtable holds pointers to all of the virtual functions in the class by address in the class.

When you hold a pointer to a parent class which is actually a derived class and call a virtual function, the vtable is accessed to get the address of the function, and runs the function in the actual derived type.

This is a big topic and you better read about is some more to learn things i haven't mentioned such as how object sizes are increased with a size of a pointer or where is the vtable actually saved

http://en.wikipedia.org/wiki/Virtual_method_table

asafrob
  • 1,838
  • 13
  • 16