C++: Struct Operations
Assume the following declaration
//--- Define a new struct type
struct Point {
int x;
int y;
};
//--- Declare some variables of type Point.
Point p1;
Point p2;
Point* paddr; // declare pointer to a Point struct
Member (field) selection - dot operator
The "." (dot) operator is used to select a member of a struct.
This operator can be applied to any expression that yields a struct
(function call, subscription, etc).
int h = p1.x;
p2.y = p1.y;
Member (field) selection - arrow operator
When using a pointer to a struct, the "->" (arrow)
operator is typically used as a more readable way to both
dereference the pointer and select a member.
See -> operator.
// The following are equivalent.
int h = paddr->x // using arrow notation.
int h = (*paddr).x; // using deref plus dot.
Assignment
A struct variable can be assigned to/from.
p1 = p2;
Parameter
A struct can be passed to a function either as a value or a reference parameter.
Large structs are sometimes passed as reference parameters to avoid
the cost of the copy, even tho the value is not going to be changed.
Returned by function
A struct may be returned by a function.
Comparison - NO
The comparison operators do not work on structs.
To compare structs, compare individual fields.
if (p1.x==p2.x && p1.y==p2.y) . . .
It is not possible to write p1==p2
.
There are good reasons to forbid comparison.
- What would a greater than comparison even mean on a Point for example.
- A bit-by-bit equal comparison is not feasible in general
because there may be padding or unfilled elements (eg in a C-string).
A subelement of array or another struct
A struct value can be used inside of another struct or as an element type
in an array.
Arithmetic operators - NO
By default none of the arithmetic operators work on structs.
I/O - NO
The I/O operators >> and
<< do not work for structs; you must read/write the fields individually.
Solutions
You may redefine operators so that
they do work with your structs. When providing functions and overloaded operators
for your struct, use the class
keyword instead -- it's what
programmers expect.
See Operator Overloading.