Unit_4: C++ Inherit, Polymorphism Flashcards
1
Q
Compare Stack vs Heap-based
A
- Heap:
- where all dynamic memory from
- call “new” -> object goes on heap
- memory on heap can be reclaimed (C++: delete, Java: garbage collected)
- heap is unorganized -> random memory allocation - Stack:
- when variables declared within a scope
- storage in stack frame (activation record) -> allocate when function is called, removed when function ended
- Separate activation record each call => routine can call multi time (recursion), each frame contains its own variable and param values
- object themselves not on the stack
2
Q
What is an activation record?
A
- pointer: stack based variable and the memory it points to is on heap
3
Q
Why No virtual method => No polymorphism
A
because without virtual -> base class would be called, breaking polymorphic behavior
4
Q
Why No pointer (as in a stack-based object) => No
polymorphism
A
because when you use stack base, the derived class object get sliced down to base class. without pointer => object lost its derived class identity
5
Q
compare virtual method in C++ vs JAVA
A
- C++: can implement pure virtual method in the class defines it
- JAVA: not possible
6
Q
What’s consequence of polymorphism?
A
- We use superclass variables to hold instances of subclasses -> issue using the instance as their actual type.
eg declare ListItem x, then put CharAtom into x, later we want to work with this directly => need downcasting into a CharAtom explicitly.
7
Q
How to safely do downcasting?
A
Add our own error checking method
Animal* aPet; aPet = new Dog;
Dog* d = dynamic_cast<Dog*>(aPet);
if (d == nullptr) {
cout «_space;“aPet was not a Dog!” «_space;endl;
}
8
Q
A