Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I would like to ask how is it possible to do typecasting and then dereferencing in C++, I mean with C++ code not C. Here, it is a part of code which simply type casted in C, how can do that in C++?

C#
bool equals_double(const void* elem1, const void* elem2){
    if (*(int*)elem1 == *(int*)elem2)



I used this code in C++ but it doesn't work:
C#
bool equals_int(const void* elem1, const void* elem2){
    if (*(static_cast<int*>(elem1)) == *(static_cast<int*>(elem2))){
        return true;
    }
    else{
        return false;
    }
}


the error is:
C++
error: static_cast from type 'const void*' to type 'int*' casts away qualifiers|
Posted
Updated 17-Oct-15 20:50pm
v5
Comments
Andreas Gieriet 17-Oct-15 17:46pm    
What does your textbook tell about casting in C++?
Regards
Andi
Philippe Mori 17-Oct-15 17:51pm    
You avoid unneccessy casting. You fonction should peobably tke doubles.... If you need casting, better to use C++ style cast list static_cast and others...
amin.j 18-Oct-15 0:54am    
I did this code for substituting the typecasting in C++ instead of the above code in C but it doesn't work. There should be a dereferencing after typy casting.

bool equals_int(const void* elem1, const void* elem2){
if (*(static_cast<int*>(elem1)) == *(static_cast<int*>(elem2))){
....
Andreas Gieriet 18-Oct-15 2:43am    
The error tells it all: "...qualifiers...": you cannot cast away constness with the static_cast operator - use ...<const int*>...
Regards
Andi
PS: Why do you change from double to int?
amin.j 18-Oct-15 2:49am    
Dear Andreas, thanks a lot it works. However, is it possible to explain it more what is the error is about and what the solution does!

1 solution

How about Google?
E.g. see http://www.cplusplus.com/doc/tutorial/typecasting/[^].
Regards
Andi
 
Share this answer
 
Comments
[no name] 18-Oct-15 12:11pm    
A 5.
Andreas Gieriet 18-Oct-15 13:42pm    
Thanks for your 5!
Cheers
Andi

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900