0

i have read about this metrial and i am still dont understand it's core e.g:

public static void Main()
{
    person []p = new person[]{new student(),new worker()}; 
}

public class person
{
    public void f1() { }
    public virtual void f2() { }
} 
public class student:person
{
     public override void f2() { }
}

public class worker:person
{
    public override void f2() { }
}

does p[0] has it's own virtual table as an instance and so p[1] with one entry with f2 so every instance has it's own virtual table ?

does every object has it's own virtual table ?

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
yoav.str
  • 1,547
  • 6
  • 33
  • 73

3 Answers3

1

Typically, there is only one vtable per type, and then each object contains a pointer to it's type's vtable. However, I believe that most inheritance implementations are undefined - i.e., it could be implemented in any way that it chooses.

Puppy
  • 144,682
  • 38
  • 256
  • 465
1

There's a comprehensive overview of how the CLR handles this here.

How the CLR Creates Runtime Objects

For C++ it's implementation-defined - @DeadMG's answer is a good general guideline, though there are interesting edge cases like multiple inheritance and inline virtual functions.

Community
  • 1
  • 1
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140
  • +1 for implementation defined: I've seen vftables get inlined into objects instead of a pointer to the vftable being set, iirc that was from some dodgy msvc code or something... – Necrolis Oct 27 '10 at 14:52
  • @Necrolis - possible due to Microsoft-specific `__declspec(novtable)` - http://msdn.microsoft.com/en-us/library/k13k85ky(v=VS.100).aspx. Another edge case, thanks. – Steve Townsend Oct 27 '10 at 14:59
0

Virtual table is tied to object's type (i.e. class). But every object (instance of a reference type) has a pointer to its type, and therefore indirectly to its vtable.

If you are interested in C#, there is a neat article here which describes .NET CLR internals: CodeProject .NET Type internals.

vgru
  • 49,838
  • 16
  • 120
  • 201