Skip to content

Commit

Permalink
Merge pull request #6 from gjbex/development
Browse files Browse the repository at this point in the history
Add example code for introspection
  • Loading branch information
gjbex authored Mar 5, 2020
2 parents 1759207 + b9a32e5 commit 6db1e30
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
3 changes: 3 additions & 0 deletions source-code/Pointers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,6 @@ Some illustrations of using pointers in C++.
* `tree_uptr.cpp`: main file to test node implementation.
* `DoubleLinkedList`: implementation of a double linked list
that requires using raw pointers.
* `runtime_vs_compile_time.cpp`: illustrates how to determine the
type of a derived class object at runtime when it is assigned to
a pointer of the parent class.
51 changes: 51 additions & 0 deletions source-code/Pointers/runtime_vs_compile_time.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#include <iostream>
#include <memory>
#include <typeinfo>

struct A {
virtual void f() const = 0;
void p() const { std::cout << "A::p()" << std::endl; }
~A() = default;
};

struct B : public A {
void f() const override { std::cout << "B::f()" << std::endl; }
void p() const { std::cout << "B::p()" << std::endl; }
};

struct C : public A {
void f() const override { std::cout << "C::f()" << std::endl; }
void p() const { std::cout << "C::p()" << std::endl; }
};

int main() {
B b;
std::cout << "B: ";
b.f();
b.p();
C c;
std::cout << "C: ";
c.f();
c.p();
std::cout << "A = B: ";
std::unique_ptr<A> a = std::make_unique<B>();
a->f();
a->p();
if (dynamic_cast<B*>(a.get())) {
std::cout << "a is a B: ";
dynamic_cast<B*>(a.get())->p();
}
if (!dynamic_cast<C*>(a.get()))
std::cout << "a is not a C\n";
std::cout << "A = B: ";
a = std::make_unique<C>();
a->f();
a->p();
if (typeid(*a.get()) != typeid(B))
std::cout << "a is not a B\n";
if (typeid(*a.get()) == typeid(C)) {
std::cout << "a is a C: ";
static_cast<C*>(a.get())->p();
}
return 0;
}

0 comments on commit 6db1e30

Please sign in to comment.