Hello, I was hoping someone might be able to clear up some questions I have on casting Objects vs Casting Pointers in C++. The first example below is compilaining that the constructor of XDeviceMotionEvent cannot construct a new XDeviceMotionEvent object from an _XEvent&.

What I dont understand about this is that if I cast the address of xEvent to a pointer of type XDeviceMotionEvent then dereference it, so that this gets fed constructor of my new XDeviceMotionEvent, it works (example 2).

I am a little confused about what exactly is going on when I cast an ObjectA to an ObjectB, vs casting ObjectA* to ObjectB*. and what the difference is between casting to a pointer and then dereferencing, and casting directly from ObjectA to ObjectB. The result here is the same, but the compiler doesn't like the first example. I understnad that casting a pointer is a much simpler operation as both are just an address, but I dont see what is going on when you cast between objects, and why the compiler cant just say "this new object is 32 bytes, the old object that its casting from is 24 bytes, so this 24 bytes, and the next 8 bytes from it are now of type T" and then just copy that memory byte for byte into the new object, as this is essentially what it will be doing in example 2.

Any explaination here would be great.


XDeviceMotionEvent motionEvent = (XDeviceMotionEvent )xEvent;

error: no matching function for call to 'XDeviceMotionEvent::XDeviceMotionEvent(_XEvent&)'
 note: candidates are: XDeviceMotionEvent::XDeviceMotionEvent()
 note:                 XDeviceMotionEvent::XDeviceMotionEvent(const XDeviceMotionEvent&)


XDeviceMotionEvent* motionEvent = *(XDeviceMotionEvent*)&xEvent;

The compiler doesn't like the first example because you're making an implicit constructor call using an argument type that isn't expected. It has nothing to do with the semantics of casting. This would fail with the same error:

XDeviceMotionEvent motionEvent ( xEvent );