File tree 2 files changed +54
-0
lines changed 2 files changed +54
-0
lines changed Original file line number Diff line number Diff line change @@ -16,3 +16,6 @@ Some illustrations of using pointers in C++.
16
16
* ` tree_uptr.cpp ` : main file to test node implementation.
17
17
* ` DoubleLinkedList ` : implementation of a double linked list
18
18
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.
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments