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

  1. Make the first option a tupe that has a def. ctor
  2. Don’t leave your variant uninitialized
  3. Use std::monostate as rthe first option - “dammy” type that can be used as a defaulr
    1. can be used to create an “optional” type

      variant<monostate, T> = "T or nothing"
      // (also <std::optional<T>>)
      

</aside>

<aside> đź’ˇ How Virtual Methods work

Screenshot 2023-11-30 at 11.46.05 AM.png

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

IMG_3224.heic

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):

IMG_3225.heic

IMG_3226.heic

</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)?

IMG_3227.heic

</aside>

But…

<aside> đź’ˇ Multiple Inheritnace

IMG_3228.heic

</aside>

Challenges: suppose

ckass D: public B: public C {
	public:
	int d;
};
D dobj; // dobj.a - which a is this?

IMG_3229.heic

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?

IMG_3230.heic

Make A a virtual base class - virtual in inheritence

IMG_3231.heic

How would this be laid out

IMG_3232.heic

<aside> đź’ˇ What does g++do ?

IMG_3233.heic

Sol’n: distance to the parent obj is stored in the vtable

</aside>