Prepare
Practice
Interview
Aptitude
Reasoning
English
GD
Placement papers
HR
Current affairs
Engineering
MCA
MBA
Online test
Login
Online Practice Test
>
CPP
« Previous
Next »
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
« Previous
Next »
Write your comments
*
*
Email must be in the form someone@domain.com
*
*
Enter the code shown above:
Please enter the code shown above
(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)
Related Content
C test (42)
C (12)
C++ for beginners (10)
C++ (20)
C++ (24)
C++ (18)
C++ (14)
C++ (12)
C++ (15)
C++ (15)
Data structure (20)
Data structure (10)
Data structure (10)
Data structure (10)
PERL (25)
VC++ (11)
Oops (30)
Mainframe (41)
Mainframe (15)
Embedded systems (15)
OOAD (49)
Advertisement
▲