tags:

views:

66

answers:

3

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 ?

+1  A: 

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.

DeadMG
@DeadMG - C++ or C# response?
Steve Townsend
@Steve Townsend: It's valid for both, afaik, although the OP's code is only C#.
DeadMG
A: 

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.

Groo
+1  A: 

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.

Steve Townsend
+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
@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