I’m studying casting in C++ and the code after is magic to me.
#include <iostream>
using namespace std;
class Base {
public:
virtual void f() { }
};
#define SOME_VALUE 8
int main() {
cout << SOME_VALUE <<endl;
getchar();
}
the output is: 8
The code is very simple, but What type of SOME_VALUE? int, or double or char?
After is more complex:
#include <iostream>
using namespace std;
class Base {
public:
virtual void f() { }
};
#define SOME_VALUE 8
int main() {
cout << (Base*)SOME_VALUE-SOME_VALUE <<endl;
getchar();
}
The output is: FFFFFFE8
Following this code, I can understand that SOME_VALUE is numeric type. I also test sizeof(SOME_VALUE) and the out put is 4. But if SOME_WHAT is numeric, how can it change to object Pointer? And how Object Pointer can minus to integer?
SOME_VALUEis a macro–it doesn’t have a type.8, however, is an integer.Use
#define SOME_VALUE ((Base*)8), if you wantSOME_VALUEto always act like aBase*.