In the first look it seems that a typedef is totally redundant as its job can be done using a macro in c++. the actual difference and the need for typedef can be clearly understood considering the usage of both these with pointers. All compiler does for a macro is to blindly replace the occurrences with the specified equivalent value before the compilation process. In case of the typedef c++ treats it as an alias in compile time for its definition.
#define intptr1 int*
typedef int* intptr;
Consider the below example: are they the same to the compiler? NO
//are following two equivalent?
intptr1 a,b;
intptr2 a,b;
Consider the macro defnition, intptr1 is simply replaced with int*
int* a, b; // intptr replaced by int*
Which means that we are declaring variable 'a' of type "int*" and variable 'b'of type "int". Something which we certainly didn't mean.
The second definition involves intptr2, which is a typedef to int*. typedefs are handelled by the C++ compiler,
and they are treated identical to the type that they stand for. Thus, there is not just a "textual substritution", but much more than that: int *a, *b; // intptr2 is treated identical to int*
another fail case:
#define intptr1 int*
typedef int* intptr2;
//Are these equivalent?
const intptr1 x;
const intptr2 y;
and they are treated identical to the type that they stand for. Thus, there is not just a "textual substritution", but much more than that: int *a, *b; // intptr2 is treated identical to int*
another fail case:
#define intptr1 int*
typedef int* intptr2;
//Are these equivalent?
const intptr1 x;
const intptr2 y;