Unit_4: C++ Inherit, Polymorphism Flashcards

1
Q

Compare Stack vs Heap-based

A
  1. 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
  2. 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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is an activation record?

A
  • pointer: stack based variable and the memory it points to is on heap
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Why No virtual method => No polymorphism

A

because without virtual -> base class would be called, breaking polymorphic behavior

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

compare virtual method in C++ vs JAVA

A
  • C++: can implement pure virtual method in the class defines it
  • JAVA: not possible
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
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 &laquo_space;“aPet was not a Dog!” &laquo_space;endl;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly