2. STRUCTURES
Collection of variables referenced with one name
A structure declaration is a blueprint (i.e., does not
allocate memory); often put in header files
struct tag
{
variable declarations;
};
Creates a new type specifier (i.e., a new data type)
Variable declarations may include any type except the
struct-type being created
Each element or variable is called a member or field
4. Structure Variable and Pointer
struct date
{
int year;
int mon;
int day;
};
date when;
date* datePtr;
Space is not allocated by struct
declarations, only by variable
definitions of that struct
5. Member Access Operators
Accessing the individual data contained in a struct
If the left hand side (LHS) operand is a struct object, use the
. (the period, pronounced “dot”)
If the LHS operand is a pointer to a struct, use the -> (formed
by the minus and greater than symbols, pronounced “arrow”)
Members are legal anywhere a variable of that type is legal
(i.e., they can be either l-values or r-values)
Members (i.e., names) are in a unique scope
Examples
when.year = 1998;
int mon = when.mon;
datePtr->day = 14;
int year = datePtr->year;
6. Struct Facts
Assignment, pass, and return copies a “patch of bits”
Initialization
date today = { 1998, 2, 14 };
Assignment (bit-by-bit copy)
when = today;
Member by member assignment (if you only want some
members)
when.year = today.year;
when.mon = today.mon;
when.day = today.day;
struct can pass as argument to function
passed by value (bit-by-bit copy)
passed by reference(address)
struct can return as value from function
7. Manipulating structs
Finding the address: &today;
Allocating structs dynamically:
date* dateVar;
dateVar = new date;
De allocating dynamic memory or variables:
delete dateVar;
9. Structure Return Values
date getDate(void)
{
date D;
cout << “enter a year: ”;
cin >> D.year;
cout << “enter a month: ”;
cin >> D.mon;
cout << “enter a day: ”;
cin >> D.day;
return D;
}
date now;
now = getDate( );
10. Nested structs(struct within structs)
structs may contain
structs
range R;
R.Start.year = 1776;
Structs cannot
contain themselves
struct range
{
date Start;
date End;
};
struct date
{
int year, mon, day;
date end; // error
};
11. STRUCTURES AND CLASSES
• Structures are usually used to hold data only,
and classes are used to hold both data and
functions.
• In C++ structures can in fact hold both data
and functions
• Major difference between class and a
structure is that in a class members are private
by default while in a structure they are public
by default.