dynamic_cast

From Wikipedia, the free encyclopedia
Jump to: navigation, search

In the C++ programming language, the dynamic_cast operator is a part of the run-time type information (RTTI) system that performs a typecast. Unlike the static_cast, the target of the dynamic_cast must be pointer or reference to class. Unlike static_cast and C-style typecast (where type check is made during compilation), a type safety check is performed at runtime. If the types are not compatible, an exception will be thrown (when dealing with references) or a null pointer will be returned (when dealing with pointers). In this regard, dynamic_cast behaves like a Java typecast.

Example code[edit]

Suppose some function takes an object of type A as its argument, and wishes to perform some additional operation if the object passed is an instance of B, a subclass of A. This can be accomplished using dynamic_cast as follows.

#include <typeinfo> // For std::bad_cast
#include <iostream> // For std::cout, std::err, std::endl etc.
 
class A {
public:
	// Since RTTI is included in the virtual method table there should be at least one virtual function.
	virtual ~A() { };
	void methodSpecificToA() { std::cout << "Method specific for A was invoked" << std::endl; };
};
 
class B : public A {
public:
	void methodSpecificToB() { std::cout << "Method specific for B was invoked" << std::endl; };
	virtual ~B() { };
};
 
void my_function(A& my_a)
{
	try
	{
		B& my_b = dynamic_cast<B&>(my_a); // cast will be successful only for B type objects.
		my_b.methodSpecificToB();
	}
	catch (const std::bad_cast& e)
	{
		std::cerr << "  Exception " << e.what() << " thrown." << std::endl;
		std::cerr << "  Object is not of type B" << std::endl;
	}
}
 
int main()
{
	A *arrayOfA[3];          // Array of pointers to base class (A)
	arrayOfA[0] = new B();   // Pointer to B object
	arrayOfA[1] = new B();   // Pointer to B object
	arrayOfA[2] = new A();   // Pointer to A object
	for (int i = 0; i < 3; i++)
	{
		my_function(*arrayOfA[i]);
		delete arrayOfA[i];  // delete object to prevent memory leak
	}
}

Console output:

Method specific for B was invoked
Method specific for B was invoked
  Exception std::bad_cast thrown.
  Object is not of type B

A similar version of my_function can be written with pointers instead of references:

void my_function(A* my_a)
{
	B* my_b = dynamic_cast<B*>(my_a);
 
	if (my_b != nullptr)
		my_b->methodSpecificToB();
	else
		std::cerr << "  Object is not B type" << std::endl;
}

See also[edit]

External links[edit]