Which of the following can perform conversions between pointers to related classes?

Options
- cast_static
- dynamic_cast
- static_cast and dynamic_cast
- cast_dynamic


CORRECT ANSWER : static_cast and dynamic_cast

Discussion Board
C++ - Static_cast and Dynamic_cast

A static_cast and dynamic_cast both performs conversion between pointers to related classes. The difference between static_cast and dynamic_cast is that, static_cast performs a cast statically at compile time. It performs no run-time checks and hence no runtime overhead.
For example,
int a = 10;
float n = static_cast<float>(a); //it behaves as 'a' was a float at compile time.

Where, dynamic_cast performs a cast 'dynamically' at runtime. It is used for handling polymorphism. Dynamic_cast makes sure that the result of the type conversion is valid and complete object of the requested class.
For example,

class Base{ };
class Derived : public Base { };

Base b, *ptrb;
Derived d, *ptrd;

ptrb = dynamic_cast*<Base *>(&d); //Works fine
ptrd = dynamic_Cast<<Derived *>(&b); //Fail

In the above example, first dynamic_cast statement will work appropriately because casting is done from derived class to base class and second dynamic_cast statement will give compilation error because base class to derived class class conversion is not allowed with dynamic_cast unless the base class is polymorphic. A polymorphic type has at least one virtual function which is declared or inherited.
For example,
class Base{virtual void dummy()}; //polymorphic class

Dynamic_cast have a significant runtime overhead.


Prajakta Pandit 01-3-2017 11:54 PM

Both static_cast and dynamic_cast can perform conversions.

Both static_cast and dynamic_cast can perform conversions between pointers to related classes. Only the difference between them is that the static_cast performs the conversion between pointers of the non-polymorphic related classes and dynamic_cast performs the conversion of the polymorphic related classes.

Nitin Durugkar 08-8-2013 06:25 AM

Write your comments


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)


Advertisement