Type Casting And Cast Operators in C++
Typecasting, or type conversion, is
a method of changing an entity from one data type to another. It is used in
computer programming to ensure variables are correctly processed by a function.
An example of typecasting is converting an integer to a string.
Example:
short
int my_short = -10;
int my_int
= (int)my_short;
(This
converts or type casts ‘short int’ my_short variable into ‘int’)
There are
primarily 2 types:
11) Implicit Type Casting
This casting happens
without your effort and is generally done in order to simplify coding and its
execution is automatic. There are two common forms of this- numeric conversions,
where two numbers of different types are used in a mathematical statement, and
one is converted to the other so that the processor can do the calculation. Mostly,
the integer casted to a float will result in a float. Sometimes, however, casting
the float to an integer and the result will be an integer (this can be done
explicitly).
22) Explicit Type Casting
This is primarily done
to reuse code & Don’t Repeat Yourself programming. The idea is that, you
can write a method that will operate on an entire class of object types,
without needing to know the specific object type. As you don’t know the object
type, the return value might be a base class type, instead of its more specific
instance type. Because of this we must cast the instance back into the more
specific type to continue the other operations, as we know that the return
result is of a more specific type. Without this behaviour you might have to
write/repeat a method in every class of an entire hierarchy in order to achieve
the desired functionality.
An example for explicit type casting:
#include <iostream>
using namespace std;
class Dummy {
double i,j;
};
class Add {
int x,y;
public:
Add (int a, int
b) { x=a; y=b; }
int result() {
return x+y;}
};
int main () {
Dummy d;
Add * add;
add = (Addition*)
&d;
cout << add->result();
return 0;
}
//Output: 0 (as x and y are initialised to zero after
calling the class pointer)
The
program declares a pointer to Addition, but then it assigns to it a
reference to an object of another unrelated type using explicit typecasting:
Casting in
C++:
Four predefined cast operators in C++
are:
· 1) const_cast operator:
§ Use: const_cast<target type>(expression)
§ ‘const_cast’ converts between types
with different const/volatile qualification
§ Only ‘const_cast’ can be used to
remove const nature or volatility
§ Usually does not perform computation
or change values
Ex.
#include<iostream>
void print(char
* str)
{std::cout<<str;}
int main()
{
const
char * c=”sample”;
print(c); // Wont work here as we are passing const char * to a char * function
print(const_cast<char
*>(c)); //This makes variable passes
to function of char * type
}
· 2) static_cast operator:
§ Use: static_cast<target type>(expression)
§ Performs all conversions allowed implicitly and also opposite
of these like void * to specific datatype, convert int, floats to enum types
and vice versa
§ Can perform conversions between pointers
and related classes (can up cast and downcast in class hierarchy)
Ex.
#include<iostream>
int main()
{
int i=2;
double
d= 3.7;
d=
static_cast<double>(i);
//Valid,
converting int I to double d
i=
static_cast<int>(d);
//Valid,converting double d to int
i(loss of decimal)
}
·
3) reinterpret_cast
operator:
§ Use: reinterpret_cast<target type>(expression)
§ This converts pointer of any type
into pointer of any other type, even of unrelated classes, result is simple
binary copy of value of one pointer to another
§ Need to handle with care the
situations where there is potential chance of data loss while type conversions
for or to ‘int’ types
Ex.
#include<iostream>
int
main()
{
int i=2;
double
d=3.7;
double
*pd=&d;
i=reinterpret_cast<int>(pd) // Valid, converted pointer to int
type, which is not possible using static_cast
}
· dynamic_cast operator:
§ Use: dynamic_cast<target type>(expression)
§ Can only be used with pointers or
references to the class or void *
§ Its purpose is to ensure that result
of the type conversion points to valid complete object of the target pointer
type
§ Dynamic cast can upcast and also, it
can downcast can use the information during the run time to reduce the possibility
of cast error
§ If conversion is not possible, exception
of bad_cast is thrown
§ It can perform all the other implicit
casts allowed on pointers (Unrelated cast conversion is invalid except for void*
conversion)
Ex.
#include<iostream>
using
namespace std;
class
A { public: virtual ~A( ) { } };
class
B:public A { };
class
C { public: virtual ~C ( ) { } };
int main()
{
A a;
B b; C c; A *pa; B*pb; C * pc;
pb=&b;
pa=dynamic_cast<A*>(pb);
cout<<”pb
up casts to pa: valid”<<pb<<pa;
pa=&b;
pa=dynamic_cast<B*>(pa);
cout<<”pa
down casts to pb: valid”<<pa<<pb;
//as
pa stores address of b, downcast
possible
pa=&a;
pa=dynamic_cast<B*>(pa);
cout<<”pa
down casts to pb: Invalid”<<pa<<pb;
//as pa stores address of a, downcast
not possible
}
Sources:
cplusplus.com
Nptel Course Programming in C++
-
Saransh Kulkarni
TY – K, 43
Brilliant! Very cogent explanations
ReplyDeleteThanks for your precious feedback.
Deletenice explaination
ReplyDeleteThank You! :)
Deletehow thoroughly written, keep posting please!
ReplyDeleteAlways!
DeleteFor my viewers!
Nicely done.
ReplyDeleteThanks!
DeleteVery good explanation👌
ReplyDeleteThanks for valuable comment!
Delete