I come from a background of C# and Java and I can't seem to understand what casting with pointers means in C++.
For example:
int x = 1;
char c = *((char*)&x);
What does it do? What it is useful for?
In both your examples you're making mistakes making the code not compile. So I'll assume you're trying to do the following:
int x = 1;
char c = *((char*)&x);
Depending on your architecture, c
will now have either the value of the least or the most significant byte of x
. In this example this would be either 0 or 1 (this can actually be used to detect the byte ordering).
Your second example won't work, cause you're trying to ignore the const
resulting in an illegal operation/bad cast (this is also called "const correctness").
Edit: Regarding your comment about "what does it mean?":
In expressions:
&somevariable
will return the address of somevariable
.
*somevariable
will assume the contents of somevariable
are the address of the actual value, which is then returned.
In declarations:
datatype
is a normal variable/object. This is passed "by value".
datatype&
is a reference. This works exactly like normal variables in Java/C# and is passed by reference.
datatype*
is a pointer. This just contains the address where the actual value is located (see above) and is essentially passed by reference as well.
Actual casts work pretty much similar to Java/C#, but pointers are just that: They point to the location of the actual value. While this might confuse you, pointers in C/C++ work pretty much like the standard variables/references used in Java/C#.
Look at this:
MyClass x; // object of MyClass
MyClass *x; // pointer to an object of MyClass - the actual value is undefined and trying to access it will most likely result in an access violation (due to reading somewhere random).
MyClass *x = 0; // same as above, but now the default value is defined and you're able to detect whether it's been set (accessing it would essentially be a "null reference exception"; but it's actually a null pointer).
MyClass &x = MyClass(); // creating a new reference pointing to an existing object. This would be Java's "MyClass x = new MyClass();"
Casting in C++ works just like casting in Java, no pointers involved.
int x = 1;
char c = (char) x; // Lose precision
However, what you are doing here:
int x = 1;
char *c = (char *)x;
is telling the compiler that the value of x
is the address of a character. It is equivalent to
char *c;
c = 1; // Set the address of c to 0x0000000000000001
There are very few times you need to do this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With