top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use of dynamic_cast in C++?

0 votes
308 views
What is the use of dynamic_cast in C++?
posted Mar 14, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes
 
Best answer

In c++ use of dynamic_cast,it can only be used with pointers and references to classes (or with void*). Its purpose is to ensure that the result of the type conversion points to a valid complete object of the destination pointer type.This naturally includes pointer upcast (converting from pointer-to-derived to pointer-to-base), in the same way as allowed as an implicit conversion.
But dynamic_cast can also downcast (convert from pointer-to-base to pointer-to-derived) polymorphic classes (those with virtual members) if -and only if- the pointed object is a valid complete object of the target type. For example:

// dynamic_cast
#include <iostream>
#include <exception>
using namespace std;
class Base { virtual void dummy() {} 
};
class Derived: public Base { int a; };
int main () {
  try {
    Base * pba = new Derived;
    Base * pbb = new Base;
    Derived * pd;
    pd = dynamic_cast<Derived*>(pba);
    if (pd==0) cout << "Null pointer on first type-cast.\n";
    pd = dynamic_cast<Derived*>(pbb);
    if (pd==0) cout << "Null pointer on second type-cast.\n";
  } catch (exception& e) {cout << "Exception: " << e.what();}
  return 0;
}

The code above tries to perform two dynamic casts from pointer objects of type Base* (pba and pbb) to a pointer object of type Derived*, but only the first one is successful.
credits: http://www.cplusplus.com/doc/tutorial/typecasting/

answer Mar 14, 2016 by Shivam Kumar Pandey
Similar Questions
0 votes

Does the below code look like valid C++, or is it a G++ bug? 5.2.7 has the dynamic_cast operator shall not cast away constness (5.2.11).

The other compilers I could check quickly (clang, icc, msvc) all reject the code, GCCs 3.3, 4.6, 4.7 and 4.8 accept the code.

class A {
};

class B : public A {
};

int main() {
 A* a;
 B* b = new B();
 a = dynamic_cast(b);
 return 0;
}
...