object oriented compiler... question

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
Stefan

object oriented compiler... question

Post by Stefan »

Ok... I made first an Scanner... after that an Parser, which return an parse tree. Noew I have to do the part wich tranlate to machine code. I have a problem:
It is an object oriented compiler... I don't know in an hierarchy of classes how to store the offsets of metods...
This problem is very big for me... I don't know how C++ or Java handles it...
For example:

class A {
  public void print() {
    // some code
  }
}

class B extends A {
   public void print() {
     // some ather code
   }
}

void function(A object) {
   object.print();
}

So I have two classes with the method print.
I don't understand how can I handle this case:

public static void main(String args[]) {
   A a=new A();
   B b=new B();
   function(a); // should be called print from class A
   function(b); // should be called print from class B
}

Does anyone have an ideea how can I know witch method print should I call in this case?
carbonBased

RE:object oriented compiler... question

Post by carbonBased »

There's probably many ways to do this.  If I recall correctly, I believe C++ keeps a "virtual table" which contains pointers to each virtual function of each class.  It's, essentially, a database of function pointers.

In this case, then, C++ would mangle the names something like _A_print and _B_print (obviously it's a little more sophisticated then that), and would have function pointers pointing to them.

Obviously, the compiler would have to have _some_ method of differentiating object A from object B, even when they are referenced the same was (as "object" in your above code).  You'd have to incorporate some form of RTTI for this, I would imagine.  I'm not sure how C++ takes care of this.

Initially, with my own compiler, I intended have all objects as structures, at the low level.

For example:

class Stuff {
  int one, two;
  print();
};

would equate to:
stuff:
  size  dd end
  one   dd 0
  two   dd 0
  print dd print_func
end:

The size is just something I added in there, to be able to tell the total size of any object, in case of a copy.

In this instance, your code will always call [stuff+12] to access the print routine.  Wether the object is defined as A or B, the print method will always reside at this location, and can be overrided whenever, without knowledge of the executing code.

Cheers,
Jeff
Stefan

RE:object oriented compiler... question

Post by Stefan »

I think I have an ideea... I can add an pointer to an object wich represents that class... so, I'll know where an object belongs to.

Thanks!
Post Reply