If I have a struct like
struct account { int account_number; };
Then what's the difference between doing
myAccount.account_number;
and
myAccount->account_number;
or isn't there a difference?
If there's no difference, why wouldn't you just use the .
notation rather than ->
? ->
seems so messy.
Put very simple :: is the scoping operator, . is the access operator (I forget what the actual name is?), and -> is the dereference arrow. :: - Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it.
A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit. A structure is a collection of variables of different data types under a single unit.
The only difference between a struct and class in C++ is the default accessibility of member variables and methods. In a struct they are public; in a class they are private. Having imparted this information, I urge you not to exploit it too heavily.
Classes and Structs (C++)The two constructs are identical in C++ except that in structs the default accessibility is public, whereas in classes the default is private. Classes and structs are the constructs whereby you define your own types.
-> is a shorthand for (*x).field
, where x
is a pointer to a variable of type struct account
, and field
is a field in the struct, such as account_number
.
If you have a pointer to a struct, then saying
accountp->account_number;
is much more concise than
(*accountp).account_number;
You use .
when you're dealing with variables. You use ->
when you are dealing with pointers.
For example:
struct account { int account_number; };
Declare a new variable of type struct account
:
struct account s; ... // initializing the variable s.account_number = 1;
Declare a
as a pointer to struct account
:
struct account *a; ... // initializing the variable a = &some_account; // point the pointer to some_account a->account_number = 1; // modifying the value of account_number
Using a->account_number = 1;
is an alternate syntax for (*a).account_number = 1;
I hope this helps.
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