Lecture - Imperative Programming TT23, X
- Factory pattern
- Implementation of OOP languages
- Object identity is the address of the chunk of memory allocated to the object
- But garbage collection and automatic memory management makes this difficult
- Instance variables of a class are stored at fixed offsets from a “base” pointer to a object
- Each object also has a pointer to a class descriptor that describes the class, e.g. the offsets for each attribute
- Methods are looked up in the class descriptor’s
vtable
, e.g.v.drive(100)
becomesv.class.vtable[0](v, 100)
- Subclasses extend the superclass’ object record and
vtable
. - Late binding of methods: need to update the specific methods of a class that the superclass calls when it has been extended
- Fragile binary interface problem: everytime a base class changes, every subclass needs to be recompiled because the record or
vtable
layout might change - Virtual lookup problem: there’s a lot of indirection looking up the code in methods, especially when there’s a big hierachy. This can be slow
- Memory management: allocating and deallocating objects as necessary
- Static allocation, memory is reserved at compile time. Very efficient but inflexible. Programs can only use a fixed amount of memory, no recursion, etc. Can use companion objects to do this in Scala.
- Stack-based allocation, each thread of execution has a stack of frames. Frame is allocated when a method is called, and the frame is popped off the stack when the method ends.
- Heap: global memory pool. Memory is allocated as needed using new. Memory is released when the program ends and when it is no longer being used. Can either be reclaimed explicitly or automatically via garbage collection.
Flashcards
What is the Factory patten in OOP?
Where the creation of objects using new
is delegated to a seperate Factory method.
How is object identity normally implemented?
Object identity is the address of the chunk of memory allocated to an object.
When implementing object oriented languages, instance variables of objects are often stored at a fixed ofset from the pointer to the object. Where is the information about where to find this offsets stored?
In a class descriptor, and the pointer to the object points to this class descriptor.
Convert v.drive(100)
to how it might look in relation to a vtable, assuming drive
is the first method in the vtable.
v.drive(100)
to how it might look in relation to a vtable, assuming drive
is the first method in the vtable.v.class.vtable[0](v, 100)
What is static allocation?
All memory is reserved at compile time. Efficient but inflexible.
What feature in Scala lets you do static allocation?
Companion classes.
What is stack-based allocation?
Each thread has a stack of frames, which contains e.g. local variables.
What is heap-based allocation?
A global memory pool that is either managed explicitely or by garbage collection.