can anyone give me an example of dynamic type checking...how do we do tht

Dani AI

Generated

asked for a simple way to do dynamic type checking. ’s post shows typeid in action, which is one of the tools you can use — but a few practical caveats make the difference between a correct approach and surprises.

typeid(expr) returns a std::type_info. When expr is an object of a polymorphic type (the class has at least one virtual function), typeid reflects the dynamic (most-derived) type; otherwise it yields the static type. Also note that type_info::name() returns an implementation-defined string (often mangled on GCC/Clang). See typeid and std::type_info for details.

For safe runtime downcasting and checks prefer dynamic_cast. It requires a polymorphic base. For pointers it returns nullptr on failure; for references it throws std::bad_cast. This is the usual idiom for “is-a” checks and then using the derived interface. See dynamic_cast.

Example (safe downcast pattern):

#include <iostream>

struct Base { virtual ~Base() = default; };
struct Derived : Base { void hello() { std::cout << "hi\n"; } };

int main() {
    Base* b = new Derived;
    if (Derived* d = dynamic_cast<Derived*>(b)) {
        d->hello();
    }
    delete b;
}

Troubleshooting notes: RTTI must be enabled (compilers can disable it with options like -fno-rtti), and relying on type_info::name() for portable type strings is fragile. If performance or memory is a concern, consider explicit type tags or the Visitor pattern instead of RTTI.

#include <cstdlib>
#include <iostream>

class Base {
};

class Derived : public Base {};

using namespace std;
int main(void)
{
   Derived* pd = new Derived;
   Base* pb = pd;
   cout << typeid( pb ).name() << endl;   //prints "class Base *"
   cout << typeid( *pb ).name() << endl;   //prints "class Derived"
   cout << typeid( pd ).name() << endl;   //prints "class Derived *"
   cout << typeid( *pd ).name() << endl;   //prints "class Derived"
   
   delete pd;
   
   return EXIT_SUCCESS;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.