Compiler Design
Compilation of OOP Features
Compilation of OOP Features
Object-Oriented Programming (OOP) languages introduce features like inheritance and polymorphism that require special compiler support to map down to standard machine code.
- Classes: A class is compiled into a struct (holding data fields) and a set of functions. Methods are translated to regular functions with an implicit
thispointer. - Inheritance: A derived class object contains the base class object at the very start of its memory layout. This allows a derived pointer to be safely cast to a base pointer.
When a base class pointer points to a derived class object, the correct function must be called dynamically at runtime.
- The compiler creates a vtable (virtual function table) for each class containing virtual functions.
- The vtable is an array of function pointers.
- Each object contains a hidden vptr (vtable pointer) as its first field.
- A virtual call
obj->f()compiles to: load vptr → look up f's index → call the pointer.
To handle exceptions (throw / catch), the compiler must generate code for stack unwinding. When an exception is thrown, all stack frames up to the handler must be cleaned up (and destructors called). The compiler generates exception tables to map code ranges to their respective catch handlers.