Reputation: 61
Having a little trouble understanding the concept of casting in C++. How does the casting work when using pointers? When is casting a Compile Time issue or a Run Time one?
// class type-casting
#include <iostream>
using namespace std;
class CDummy {
float i,j;
};
class CAddition {
int x,y;
public:
CAddition (int a, int b) { x=a; y=b; }
int result() { return x+y;}
};
int main () {
CDummy d;
CAddition * padd;
padd = (CAddition*) &d;
cout << padd->result();
return 0;
}
Upvotes: 0
Views: 121
Reputation: 122133
I want to know more about casting in c++ in general. It looks way more harder than that of Java which has type checking and JVM.
C++ does check types. By using a c-style cast, you explicitly ask to bypass all security the type systems gives you. You should not use c-style casts in C++, but rather static_cast
, dynamic_cast
and in rare cases const_cast
and in even more rare cases reinterpret_cast
.
If you replace your c-style cast
padd = (CAddition*) &d;
with the C++ cast:
padd = static_cast<CAddition*>(&d);
then the compiler will tell you that what you are doing is wrong:
prog.cc:19:36: error: invalid static_cast from type 'CDummy*' to type 'CAddition*'
padd = static_cast<CAddition*>(&d);
I don't think it can be more clear: A CDummy*
is not a CAddition*
so you should not cast between those types.
Because you do, your code has undefined behavior. Neither the C++ standard nor compilers bother to do anything meaningful with code that has undefined behavior (hence the name: it is simply not defined what you will get).
PS In your example you can provide a conversion:
class CAddition {
int x,y;
public:
CAddition (const CDummy& cd) : x(cd.i),y(cd.j) {}
CAddition (int a, int b) : x(a),y(b) {}
int result() { return x+y;}
};
Using such a converting constructor you can create a CAddition
from a CDummy
easily (you would need to make the members public
in CDummy
or provide some other means to access them to make this work).
PPS I was a bit sloppy when above I told you that the C++ casts are safer. They still make a good tool to shoot yourself in the foot. Needing to cast is usually a code/design smell. Don't fall into the trap of silencing compiler warnings / errors by putting casts in your code. This may be fine in Java, but it makes things just worse in C++.
Upvotes: 3