Dynamic_cast

The syntax of dynamic cast:
dynamic_cast< Type* >(ptr)

This dynamic_cast will try to cast ptr to a pointer of type Type*. This cast is executed at runtime.let us try to compile

#include<iostream>
using namespace std;

class Base
{
public:
    ~Base(){};
};
class Der : public Base {};

int main()
{
    Base* base = new Der;
    Der* der = dynamic_cast<Der*>(base); // OK

    Base* base1 = new Base();
    der = dynamic_cast<Der*>(base1); //
    if(der == NULL)
    cout<<"badtype csat"<<endl;
    return 0;
}

It will not compile, giving error
dynacas.cpp: In function ‘int main()’:
dynacas.cpp:15:39: error: cannot dynamic_cast ‘base’ (of type ‘class Base*’) to type ‘class Der*’ (source type is not polymorphic)
Der* der = dynamic_cast<Der*>(base); // OK
^
dynacas.cpp:18:35: error: cannot dynamic_cast ‘base1’ (of type ‘class Base*’) to type ‘class Der*’ (source type is not polymorphic)
der = dynamic_cast<Der*>(base1); //

Hence dynamic_cast works only for polymorphic classes. so to compile we have to make Class B polymorphic. Like Below

class Base
{
public:
    virtual ~Base(){};
};
class Der : public Base {};

int main()
{
    Base* base = new Der;
    Der* der = dynamic_cast<Der*>(base); // OK

    Base* base1 = new Base();
    der = dynamic_cast<Der*>(base1); //
    if(der == NULL)
    cout<<"badtype csat"<<endl;
    return 0;
}

Note: (1) When dynamic_cast fails in case of casting pointer it returns NULL.

#include<iostream>
using namespace std;

class Base
{
public:
  virtual  ~Base(){};
};
class Der : public Base {};

int main()
{
    Der* der = new Der();
    Base* base1 = new Base();
    der = dynamic_cast<Der*>(base1); //
    if(der == NULL)
    cout<<"badtype csat"<<endl;
    return 0;
}

Here der = dynamic_cast<Der*>(base1); return NULL to der,as the cast is invalid because base1 is not pointing to Der class object. if we make base1, to point to der object then it will succeed.

#include<iostream>
using namespace std;

class Base
{
public:
  virtual  ~Base(){};
};
class Der : public Base {};

int main()
{
    Der* der = new Der();
    Base* base1 = new Base();
    base1 = der;
    der = dynamic_cast<Der*>(base1); //
    if(der == NULL)
    cout<<"badtype csat"<<endl;
    return 0;
}

(2) When dynamic_cast fails in case of casting reference it gives exception of std::bad_cast.

#include<iostream>
#include<typeinfo>
using namespace std;

class Base
{
public:
  virtual  ~Base(){};
};
class Der : public Base {};

int main()
{
  try
  {
    Base base;
    Der& der = dynamic_cast<Der&>(base);
  }
  catch (std::bad_cast& bad)
  {
     std::cerr << "bad casting: " << bad.what() << '\n';
  }
  return 0;
}

output:
bad casting: std::bad_cast



Related Contents to follow