-1

I was working on project where in by mistake I typed different class name while doing dynamic_cast and it worked didn't throw any exception and problem occurred in different module. In a nutshell we have a class hierarchy where in Class B is derived from base class A and both has virtual functions. There is separate base class C with virtual function. Now while doing dynamic_cast on pointer to C I mistyped to A as in below code and it worked.

My question is why dynamic_cast is now throwing exception in this case as it should throw an exception since I am trying to cast the input pointer to completely different class pointer. I ran it on http://ideone.com/Fpb3t1 here too no exception was thrown.

#include <iostream>

using namespace std;

class A
{
    public:
        virtual void method() {;}
};

class B : public A
{
};

class C
{
    public:
        virtual void no(int arg) {;}
};

int main()
{
    C obj;
    A* ptr = NULL;
    try
    {
        C *cptr = &obj;
        ptr = dynamic_cast<A*> (cptr);
    }
    catch (...)
    {
        std::cout << std::endl << "NO EXCEPTION" << std::endl;
    }
    return 0;
}

Thanks

user3494614
  • 603
  • 1
  • 7
  • 20
  • 3
    Read about what [`dynamic_cast`](http://en.cppreference.com/w/cpp/language/dynamic_cast) actually does. – nwp May 17 '17 at 13:41

1 Answers1

2

A failed dynamic_cast on a pointer returns nullptr, it does not throw. See here for more details.

Community
  • 1
  • 1
Steve Townsend
  • 53,498
  • 9
  • 91
  • 140