How many types of casting are there in C++?
When is a dynamic cast,static_cast,reinterpret cast used?

Answer Posted / shakti singh khinchi

There are 4 types of castings in C++ which is known as RTTI
(Run Time Type Identification).
Dynamic cast: When dynamic_cast cannot cast a pointer
because it is not a complete object of the required class
-as in the second conversion in the previous example- it
returns a null pointer to indicate the failure. If
dynamic_cast is used to convert to a reference type and the
conversion is not possible, an exception of type bad_cast is
thrown instead.

dynamic_cast can also cast null pointers even between
pointers to unrelated classes, and can also cast pointers of
any type to void pointers (void*).

static cast:static_cast can perform conversions between
pointers to related classes, not only from the derived class
to its base, but also from a base class to its derived. This
ensures that at least the classes are compatible if the
proper object is converted, but no safety check is performed
during runtime to check if the object being converted is in
fact a full object of the destination type.

const cast:This type of casting manipulates the constness of
an object, either to be set or to be removed

reinterpret cast;reinterpret_cast converts any pointer type
to any other pointer type, even of unrelated classes. The
operation result is a simple binary copy of the value from
one pointer to the other. All pointer conversions are
allowed: neither the content pointed nor the pointer type
itself is checked.

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why the usage of pointers in C++ is not recommended ?

1092


Describe the advantages of operator overloading?

760


an integer constant must have atleast one a) character b) digit c) decimal point

775


What is the latest c++ version?

809


What are c++ variables?

763


What is the disadvantage of using a macro?

790


I want to write a C++ language program that: 1. Reads in the size of a square from the screen; 2. Prints a hollow square of that size out of “-“, “|” and blanks on screen; 3. Prints the same hollow square onto a text file. The program should work for squares of all side sizes between 1 and 20.

2510


What is virtual base class?

751


Are php strings immutable?

778


What is else syntax in c++?

841


How long it will take to learn c++?

788


What are the different types of polymorphism in c++?

814


Describe protected access specifiers?

878


What is the difference between prefix and postfix versions of operator++()?

797


What is a constructor in c++ with example?

805