dynamic_cast conversion

From Cppreference

Jump to: navigation, search

Converts between types when no implicit conversion exists.

Contents

[edit] Syntax

dynamic_cast < new_type > ( expression )

All expressions return an value of type new_type.

[edit] Explanation

All above conversion operators compute the value of expression, convert it to type and return the resulting value. Each conversion can take place only in specific circumstances or the program is ill formed.

Casts type to an non-equivalent type using run-time check if required. Implicit conversions of cv-qualifiers can also be applied, however neither constness nor volatility can be casted away. Run-time check is performed when casting a polymorphic class to one of its base classes.

If the casted type is a pointer, the pointed object is checked whether it is the requested base class. If the check succeeds, pointer to the requested base class is returned, otherwise NULL pointer is returned.

If the casted type is a reference, the pointed object is checked whether it is the requested base class. If the check succeeds, reference to the requested base class is returned, otherwise std::bad_cast is thrown.

[edit] Keywords

dynamic_cast

[edit] Example

#include <iostream>
 
struct Base {
    virtual ~Base() {}
    virtual void name() {}
};
 
struct Derived: Base {
    virtual ~Derived() {}
    virtual void name() {}
};
 
struct Some {
    virtual ~Some() {}
};
 
int main() 
{
    Some *s = new Some;
    Base* b1 = new Base;
    Base* b2 = new Derived;
 
    Derived *d1 = dynamic_cast<Derived*>(b1);
    Derived *d2 = dynamic_cast<Derived*>(b2);
    Derived *d3 = dynamic_cast<Derived*>(s);
    Base *d4 = dynamic_cast<Base*>(s);
 
    std::cout << "'b1' points to 'Derived'? : " << (bool) d1 << '\n';
    std::cout << "'b2' points to 'Derived'? : " << (bool) d2 << '\n';
    std::cout << "'s' points to 'Derived'? : " << (bool) d3 << '\n';
    std::cout << "'s' points to 'Base'? : " << (bool) d4 << '\n';
}

Output:

i = 4
type::i = 4
'b1' points to 'Derived'? : false
'b2' points to 'Derived'? : true
's' points to 'Derived'? : false
's' points to 'Base'? : false

[edit] See also