FCI-Helwan blog

Just another FCI-H weblog

Casting in C++

There are 4 types to convert from type to type (Casting) as demonstrated below

1. The standard cast to convert one type to another.
2. There is a special cast to do away with the const type-modification
3. A third cast is used to change the interpretation of information
4. There is a cast form which is used in combination with polymorphism

1 – The first (static_cast) is to convert from one type to another like from double to int.
Example 1
int anInteger = 0;
double aDouble = 12.75;
anInteger = static_cast<int>(aDouble);

Example 2
What’s the situation in where the arithmetic assignment operators used
in mixed type like:
anInteger+= aDouble; //anInteger = anInteger + aDouble;
Let’s see what happens behind the scene
anInteger = static_cast<int>(aDouble) + anInteger; //done if you cast anInteger to double

2- The second (const_cast) is to convert from a constant variable to a non constant variable.

Example 1
If I’ve function like that
void ShowText(char *c)
{
printf(“%s\n”, c);
}

And I want to pass it a parameter like that
char const fci[] = “Hello, FCI-H!”;
ShowText(fci); //error
If I try that, Compile complains and shoots this error “Error
1 error C2664: ‘ShowText’ : cannot convert parameter 1 from ‘const char [14]’
to ‘char *’”

So, we should do that
ShowText(const_cast<char*>(fci)); //no error and it prints Hello, FCI-H!

3- The third (reinterpret_cast) is to convert from any integral type to any pointer type and vice versa, but it does not work with constants (see No. 2). Plus it’s very unsafe, try to not use it.There is a practical use of reinterpret_cast is in hash function, because it generates two indexes for two different values rarely end up with the same index and it’s allow pointers to be treated as integral type.

Example 1
void pointerToInteger(void *ptr)
{
int aNumber = reinterpret_cast<int>(ptr);
printf(“%d\n”, aNumber * 2 );
}
Your assignment is to know how to call this function :p

4- The fourth is (dynamic_cast) is to convert from base class pointer to derived class pointer or from base class reference to derived class reference. But it should be one virtual function at least in the base class. (I’ll talk about it in details in the next article after Allah willing).

To be continued…

Advertisements

February 2, 2007 - Posted by | C/C++

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: