Question

I am developing a compiler for an object oriented language targeted on a virtual machine I wrote that I am using as a cross platform abstraction layer. I am sort of confused about how inherited methods works. Lets say I had the following lines of C# code.

class myObject : Object {
public int aField;
public override string ToString() { 
    return "Dis be mah object";
} 
public void regularMethod() { }
}
Object test = new myObject();
Console.WriteLine(test.ToString());

Now this would output 'Dis be mah object'. If I called regularMethod however the compiled code would in reality do something like this:

struct myObject {
    public int aField;
}

public static void regularMethod(ref myObject thisObject)
{
}

How would the inherited method ToString be handled after compilation? The compiler could not do what I did above with regularMethod, because if it did then 'Dis be mah object' would only be returned when creating myObject types and not plain Object types. My guess is that the struct myObject would contain a function pointer/delegate that would get assigned when a new instance is created.

Was it helpful?

Solution

If you are dealing with static overloading, it is really simple: you bind to the correct implementation when processing the code.

But, if you are working with dynamic overloading, you must decide things at runtime. For this you need to use dynamic dispatch, using the real object type. This is the same thign that is done with method overriding.

Dynamic dispatching is not the same as late binding. Here, you are chosing an implementation and not a name for your operation (despite the fact that this binding will occur at compile time, the implementation will only occur at runtime).

Staticly, you would only bind to implementation of the declared type of the object. It is done at compile time.

The are some mechanisms you could use to achieve the dynamic dispathing, it will dictate your language paradigm.

Is your language typed? Weakly typed?

C++, for instance, offers the two types of dispatch I mentioned. For the dynamic one (which I believe is the one you are interested), it uses a virtual table to do the mapping for one class. Each instance of that class will point have a pointer to that vtable.

  • Implementing

The vtable (one for all objects of same class) will have the addresses of all dynamicly bound methods. One of those addresses will be fetched from this table when a call is made. Type-compatible objects have tables with addresses with the same offset for the methods of all compatible classes.

Hope I've helped.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top