Skip to content

Commit 6db1e30

Browse files
authored
Merge pull request #6 from gjbex/development
Add example code for introspection
2 parents 1759207 + b9a32e5 commit 6db1e30

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

source-code/Pointers/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,6 @@ Some illustrations of using pointers in C++.
1616
* `tree_uptr.cpp`: main file to test node implementation.
1717
* `DoubleLinkedList`: implementation of a double linked list
1818
that requires using raw pointers.
19+
* `runtime_vs_compile_time.cpp`: illustrates how to determine the
20+
type of a derived class object at runtime when it is assigned to
21+
a pointer of the parent class.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include <iostream>
2+
#include <memory>
3+
#include <typeinfo>
4+
5+
struct A {
6+
virtual void f() const = 0;
7+
void p() const { std::cout << "A::p()" << std::endl; }
8+
~A() = default;
9+
};
10+
11+
struct B : public A {
12+
void f() const override { std::cout << "B::f()" << std::endl; }
13+
void p() const { std::cout << "B::p()" << std::endl; }
14+
};
15+
16+
struct C : public A {
17+
void f() const override { std::cout << "C::f()" << std::endl; }
18+
void p() const { std::cout << "C::p()" << std::endl; }
19+
};
20+
21+
int main() {
22+
B b;
23+
std::cout << "B: ";
24+
b.f();
25+
b.p();
26+
C c;
27+
std::cout << "C: ";
28+
c.f();
29+
c.p();
30+
std::cout << "A = B: ";
31+
std::unique_ptr<A> a = std::make_unique<B>();
32+
a->f();
33+
a->p();
34+
if (dynamic_cast<B*>(a.get())) {
35+
std::cout << "a is a B: ";
36+
dynamic_cast<B*>(a.get())->p();
37+
}
38+
if (!dynamic_cast<C*>(a.get()))
39+
std::cout << "a is not a C\n";
40+
std::cout << "A = B: ";
41+
a = std::make_unique<C>();
42+
a->f();
43+
a->p();
44+
if (typeid(*a.get()) != typeid(B))
45+
std::cout << "a is not a B\n";
46+
if (typeid(*a.get()) == typeid(C)) {
47+
std::cout << "a is a C: ";
48+
static_cast<C*>(a.get())->p();
49+
}
50+
return 0;
51+
}

0 commit comments

Comments
 (0)