Also, why is the pointer created like this rather than the traditional style shown here. i.e. myStruct *ptr;
It's a reference, not a pointer, that is created with myStruct& var = obj1;
The same rationale applies to pointers, however. A lot of C++ programmers prefer myStruct* ptr
over myStruct *ptr
, myStruct& ref
over myStruct &ref
. The compiler doesn't care which you use. This style preference is for the reader of the code.
The reason for putting the asterisk or ampersand with the type rather than the variable is because that asterisk or ampersand is logically a part of the type. The type of ptr
is pointer to myStruct
. A potential problem arises with this scheme: Type* ptr1, ptr2;
Because of rules inherited from C, ptr2
isn't a pointer. It's just an int
.
There's an easy solution to this problem. Don't do that! In general, it is better to declare one variable per declaration, with an exception for simple things like int i,j,k;
Don't mix pointers and non-pointers.