Recall:
using Enermy = variant<Turtle, Bullet>
Enermy e {Turtle{}};
// Discriminating the value
if(holds_alternative<Turtle>(e)) {
cout << "Turtle";
}
else...
Extracting the value
try {
Turtle t = get<Turtle>(e);
// use t ...
} catch(bad_variant_access &) {
// it's not a Turtle ...
}
A variant is like a union, but type-safe. Attempting to store as one type & fetch as another will throw. If a variant is left uninitialized, the first option in the variant is default-constructed to initialize the variant. - compiler error if first option is not default-constructor
<aside> đź’ˇ Options
can be used to create an “optional” type
variant<monostate, T> = "T or nothing"
// (also <std::optional<T>>)
</aside>
<aside> đź’ˇ How Virtual Methods work
What’s the difference
Do they look the same in memory ?
cout << sizeof(v) << ' ' << sizeof(w);
// 8 16 ???
First note: 8 is space for 2 ints - No space for f method
isHeavy is virtual ⇒ choice of which version to run is based on the type of the actual object → which the compiler won’t throw in advance
For each class with virtual methods, the cmpier creates table of f’n ptrs (the vtable):
</aside>
<aside> đź’ˇ Calling a virtual method:
at run-time
→ virtual f’n calls incur a small overhaead cost in time.
Also: Having ≥ 1 virt. f’n adds a vptr to the obj
→ classes with no virt. f’ns produce smaller objs than if someone virtual - space cost
Concretelym how is an object laid out? Compiler-dependent
Why did we put the vptr first in the obj and not somewhere else(eg. last)?
</aside>
But…
<aside> đź’ˇ Multiple Inheritnace
</aside>
Challenges: suppose
ckass D: public B: public C {
public:
int d;
};
D dobj; // dobj.a - which a is this?
Need to specify debj.B::a or dobj.C::a
But if B & C inherit from A, should there be one A part of D or two(default)?
Should B::a, C::a be trhe same or different?
Make A a virtual base class - virtual in inheritence
How would this be laid out
<aside> đź’ˇ What does g++do ?
Sol’n: distance to the parent obj is stored in the vtable
Diagramne doesn’t look like all of A, B, C, D simultaneously
D *d = new D;
A *a = d; // changes the addr
static/dynamic acst eill also do this
reinterpret_cast will not
</aside>