Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++ what does this construction mean "InterceptionKeyStroke &kstroke = * (InterceptionKeyStroke *) &stroke"?

Tags:

c++

pointers

I am a novice in C++ and don't understand this construction.

InterceptionKeyStroke &kstroke = * (InterceptionKeyStroke *) &stroke

I know that & = pointer. But what does this mean?

* (InterceptionKeyStroke *)
like image 454
Alex Sv. Avatar asked Dec 10 '22 07:12

Alex Sv.


2 Answers

Breaking it down:

InterceptionKeyStroke     // a type...
&                         // ...which is by reference
kstroke                   // named 'kstroke'
=                         // bound to (since references are bound)
*                         // something that a pointer points to
(InterceptionKeyStroke*)  // "I know what the type is!" cast
&                         // address of...
stroke                    // ...variable named 'stroke'

So the *(InterceptionKeyStroke*) is casting to a pointer, and then dereferencing the pointer.

like image 187
Eljay Avatar answered Feb 24 '23 16:02

Eljay


I know that & = pointer.

Your knowledge is incomplete. & has multiple meanings in C++. The & you refer to is the address-of operator, as in:

int i = 0;
int* ptr = &i; // `ptr` contains address of `i`

In InterceptionKeyStroke &kstroke, the & is used to declare a reference, and only the second &, i.e. the one in * (InterceptionKeyStroke *) &stroke is the address-of operator I mentioned above.

But what does this mean?

* (InterceptionKeyStroke *)

It's a C-style cast which means that a pointer should be interpreted as if it was an InterceptionKeyStroke *. The result of that operation is then dereferenced, via the dereference operator * at the left, to get an InterceptionKeyStroke object.

So the entire InterceptionKeyStroke &kstroke = * (InterceptionKeyStroke *) &stroke line is as if you told the compiler the following:

"Let kstroke be a reference to InterceptionKeyStroke, and let that reference refer to the stroke object. And yes, I know that when I take the address of stroke, then I get a pointer that doesn't technically point to an InterceptionKeyStroke. So please just interpret it as if it pointed to an InterceptionKeyStroke, because I know that it does. Now that we've established it's an InterceptionKeyStroke pointer we are talking about, dereference that pointer to obtain the object for the reference to refer to."

I should mention that this code looks very fishy. How comes stroke isn't already an InterceptionKeyStroke in the first place? What's the relationship between InterceptionKeyStroke and the type of stroke? I have a strong feeling that you've got undefined behaviour in your program, because the C-style cast subverts the compiler's error-detection mechanism. If you lie to the compiler, then anything can happen.

like image 30
Christian Hackl Avatar answered Feb 24 '23 16:02

Christian Hackl