midterm review Thursday
midterm exam Friday, here
how does g++ implement: inheritance & virtual
learn how to explore this question
class A {
public:
int a;
};
class B : public A {
public:
int b;
};
#include <iostream>
int main() {
B x;
std::cout << &x.a << " " << &x.b << std::endl;
A *pa = &x;
std::cout << pa << " " << &x << std::endl;
}
struct A { int a; };
struct B { int b; };
struct C : public A, public B { int c; };
#include <iostream>
int main() {
C x;
std::cout << &x.a << " " << &x.b << " " << &x.c << std::endl;
A *pa = &x;
B *pb = &x;
C *pc = &x;
std::cout << pa << " " << pb << " " << pc << std::endl;
}
#include <iostream>
struct A {
virtual void foo() { std::cout << "A" << std::endl; }
};
struct B : public A {
virtual void foo() override { std::cout << "B" << std::endl; }
};
int main() {
B b;
A *pa = &b;
pa->foo();
}
how does g++ know which to invoke?
Linux kernel: struct file
#include <iostream>
struct A {
virtual void foo() { std::cout << "A" << std::endl; }
virtual void bar() { }
void not_virtual();
};
struct B : public A {
virtual void foo() override { std::cout << "B" << std::endl; }
};
g++ -fdump-class-hierarchy -c
gdb: info vtbl
q: how does gdb implement this?
q: what’s the cost of calling a virtual function?
#include <iostream>
struct A {
virtual void foo() { std::cout << "A" << std::endl; }
~A() { std::cout << "~A" << std::endl; } // BAD
};
struct B : public A {
virtual void foo() override { std::cout << "B" << std::endl; }
~B() { std::cout << "~B" << std::endl; }
};
int main() {
B *pb = new B;
A *pa = pb;
delete pa;
}
what’s the output? mark destructors as virtual
!
mark every method and destructor as virtual
?
performance
understand the cost of C++ abstractions
learn how to explore memory layout details
see also “Inside the C++ Object Model” by Stanley B. Lippman