1

At a high level, I understand that an interface is a way of saying

Just do this, I don't care how

In other words, it basically allows you to program declaratively instead of imperatively. You make your code more flexible when parts of it can tell other parts of it what to do, not how to do it.

I grok that concept when it comes to high-level languages like Java.

However, I am curious how compilers deal with interfaces. This may be a bigger question than I realize.

Here's my theory: It's based upon an offset in RAM.

As an example, when an object is created that implements the ICompare interface which includes the Compare method, then the compiler knows to put that Compare method at a 16 byte offset of where that object starts in RAM. In fact, every object that implements the ICompare method has its Compare method at the 16th byte. That way, when other code uses that interface to call the Compare method, the system knows to perform the instructions at the 16th byte of that object.

Is that how a compiler handles interfaces (using a standard location in every object) or does it use some kind of lookup table to know where an object's Compare method is? Or some other method entirely?

  • 5
    So the high level answer is to research 'vtables'. There are ways to optimize out vtables, but in general that's the concept you're looking for. – sircodesalot Nov 16 '17 at 19:03
  • https://blogs.msdn.microsoft.com/vancem/2006/03/13/digging-into-interface-calls-in-the-net-framework-stub-based-dispatch/ – Hans Passant Nov 16 '17 at 19:39
  • Great comments, thank you. This answer was helpful for me to understand vtables better : https://stackoverflow.com/a/3555290/2363207. And this comment was interesting at the MSDN link: ".NET IL defines something called a MethodImpl Table which is a table that for a class, maps interface methods to method implementations." –  Nov 16 '17 at 20:10

1 Answers1

0

For anyone else interested in this question, here is an EXCELLENT video with a visual explanation of how vtables are actually implemented in C++. The first four bytes of an object can point to a vtable that points to the correct method to use for that particular class.

Thanks @sircodesalot for the tip.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • An object with virtual member functions can be stored anywhere; static, automatic (stack) or heap (dynamically allocated. It always still has an implicit `vtable` pointer as the first member regardless of where it's stored. See also [How do objects work in x86 at the assembly level?](https://stackoverflow.com/questions/33556511/how-do-objects-work-in-x86-at-the-assembly-level) – Peter Cordes Nov 16 '17 at 22:53
  • Excellent answer on that post, thank you for the link. I love when answers give you bite sized snippets of code that succinctly prove a point. It shows they were very well thought out. Thanks! –  Nov 17 '17 at 02:43