#include#include class Example { public: int value; }; void logObject(const void* object) { const std::type_info& type = typeid(*reinterpret_cast (object)); std::cout << "Object of type " << type.name() << " logged.\n"; } int main() { Example example{123}; logObject(&example); return 0; }
#includeIn this example, we have a Base class and two derived classes, Derived1 and Derived2. We also have a printType function that takes a Base object and uses GetType to determine the type of that object, and then calls the appropriate printType function on that object. Finally, we have a main function that creates instances of Base, Derived1, and Derived2, and passes them to printType to demonstrate the dynamic dispatch system. The package library for GetType is the C++ standard library.#include class Base { public: virtual void printType() { std::cout << "Base\n"; } }; class Derived1 : public Base { public: virtual void printType() { std::cout << "Derived 1\n"; } }; class Derived2 : public Base { public: virtual void printType() { std::cout << "Derived 2\n"; } }; void printType(const Base& object) { const std::type_info& type = typeid(object); if (type == typeid(Base)) { object.printType(); } else if (type == typeid(Derived1)) { static_cast (object).printType(); } else if (type == typeid(Derived2)) { static_cast (object).printType(); } } int main() { Base base; Derived1 derived1; Derived2 derived2; printType(base); printType(derived1); printType(derived2); return 0; }