I am very new to C++. Currently I am reviewing a source code where I saw some typecasting, but I didn’t understand it.
Here is the code.
struct str {
char *a;
int b;
};
class F {
public:
char* val;
};
F f1;
Can anyone explain the below Assignement Please.or is that typecasting valid??
str* ptr = (str*) f1->val;
It means “pretend that the
valpointer points to an object of typestr, even though it’s declared to point to a completely different typechar; give me that pointer and trust that I know what I’m doing”.That’s assuming that the real code either declares
F * f1;, or accesses it asf1.val; the code you’ve posted won’t compile.If the pointer really does point to an object of the correct type, then it’s valid; otherwise, using the pointer will cause the program to fail in all sorts of catastrophic ways.
Typecasting is something that should very rarely be necessary. If you really do need it, you should never (as in absolutely never, under any circumstances) use that C-style cast; it means “force the conversion with no checks whatsoever, as long as there’s some way to do it, even if it makes absolutely no sense”. Use
static_castordynamic_castwhen you can, andreinterpret_castorconst_castwhen you’re doing something really dodgy. And don’t use any of them unless you know what you’re doing, and have a very good reason for circumventing the type system.