Lecture 02: Structures CS 112: Object-Oriented Programming
Structures
Dr. Zahid Halim
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Structure
• A Structure is a container, it can hold a bunch of things.
– These things can be of any type.
• Structures are used to organize related data (variables) into a
nice neat package.
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Example - Student Record
• Student Record:
– Name a string
– HW Grades an array of 3 doubles
– Test Grades an array of 2 doubles
– Final Average a double
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Structure Members
• Each thing in a structure is called member.
• Each member has a name, a type and a value.
• Names follow the rules for variable names.
• Types can be any defined type.
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Example Structure Definition
struct StudentRecord {
char *name; // student name
double hw[3]; // homework grades
double test[2]; // test grades
double ave; // final average
};
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Using a struct
• By defining a structure, you create a new data type.
• Once a struct is defined, you can create variables of the new
type.
StudentRecord stu;
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Accessing Members
• You can treat the members of a struct just like
variables.
• You need to use the member access operator '.'
(pronounced "dot"):
cout << stu.name << endl;
stu.hw[2] = 82.3;
stu.ave = total/100;
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Structure Assignment
• You can use structures just like variables:
StudentRecord s1,s2;
s1.name = "Joe Student";
…
s2 = s1;
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Be Careful
• If a member is a pointer, copying means copying the
pointer (not what is pointed to).
"Joe Student"
name
hw
test
ave
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Probably not what you want
StudentRecord s1,s2;
s1.name = "Joe Student";
…
s2 = s1;
s2.name = "Jane Doe";
// now s1.name and s2.name are both
// "Jane Doe"
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Pointers to Structures
• Pointers to structures are used often.
• There is another member access operator used with
pointers: ->
StudentRecord *sptr;
…
cout << "Name is" << sptr->name;
cout << "Ave is " << sptr->ave;
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Other stuff you can do with a struct
• You can also associate special functions with a structure (called
member functions).
• A C++ class is very similar to a structure, we will focus on
classes.
– Classes can have (data) members
– Classes can have member functions.
– Classes can also hide some of the members (functions and data).
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Structure Definitions
• Structures
– Aggregate data types built using elements of other types
Structure tag
struct Time {
int hour; Structure members
int minute;
int second;
};
– Members of the same structure must have unique names
– Two different structures may contain members of the same name
– Each structure definition must end with a semicolon
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Structure Definitions
• Self-referential structure
– Contains a member that is a pointer to the same structure type
– Used for linked lists, queues, stacks and trees
• struct
– Creates a new data type that is used to declare variables
– Structure variables are declared like variables of other types
– Example:
Time timeObject, timeArray[ 10 ],
*timePtr, &timeRef = timeObject;
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Accessing Members of Structures
• Member access operators:
– Dot operator (.) for structures and objects
– Arrow operator (->) for pointers
– Print member hour of timeObject:
cout << timeObject.hour;
OR
timePtr = &timeObject;
cout << timePtr->hour;
– timePtr->hour is the same as ( *timePtr ).hour
– Parentheses required: * has lower precedence than .
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
1 // Fig. 6.1: fig06_01.cpp
2 // Create a structure, set its members, and print it.
3#include <iostream>
5 using std::cout;
6 using std::endl;
8 struct Time { // structure definition
9 int hour; // 0-23
10 int minute; // 0-59
Creates the user-defined structure type Time
11 int second; // 0-59
with three integer members: hour, minute
12 }; and second.
13 2. Create a struct data type
14 void printMilitary( const Time & ); // prototype
15 void printStandard( const Time & ); // prototype
16
17 int main()
18 {
19 Time dinnerTime; // variable of new type Time
20
21 // set members to valid values
22 dinnerTime.hour = 18;
23 dinnerTime.minute = 30;
24 dinnerTime.second = 0;
25
26 cout << "Dinner will be held at ";
27 printMilitary( dinnerTime );
Dinner will be held at 18:30 military
28 cout << " military time,\nwhich is ";
time,
29 printStandard( dinnerTime );
which is 6:30:00 PM standard time.
30 cout << " standard time.\n";
31
32 // set members to invalid values
33 dinnerTime.hour = 29;
34 dinnerTime.minute = 73;
35
36 cout << "\nTime with invalid values: ";
37 printMilitary( dinnerTime );
Time with invalid values: 29:73
38 cout << endl;
39 return 0;
40 }
41
42 // Print the time in military format
43 void printMilitary( const Time &t )
44 {
45 cout << ( t.hour < 10 ? "0" : "" ) << t.hour << ":"
46 << ( t.minute < 10 ? "0" : "" ) << t.minute;
47 }
48
49 // Print the time in standard format
50 void printStandard( const Time &t )
51 {
52 cout << ( ( t.hour == 0 || t.hour == 12 ) ?
53 12 : t.hour % 12 )
54 << ":" << ( t.minute < 10 ? "0" : "" ) << t.minute
55 << ":" << ( t.second < 10 ? "0" : "" ) << t.second
56 << ( t.hour < 12 ? " AM" : " PM" );
57 }
Dinner will be held at 18:30 military time,
which is 6:30:00 PM standard time.
Time with invalid values: 29:73
Lecture 02: Structures CS 112: Object-Oriented Programming
Functions in Structures
• We can also use functions in structures
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Unions and Enumerations
Dr. Zahid Halim
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Enumerated types
• An enumeration is a “data type” in which labels for all
possible values of the type can be listed
• The type declaration consists of the keyword enum
followed by the name of the new type and a block of
code in which labels for all values of the type are listed
• Syntax:
enum NewTypeName {value1, value2, … , valueN};
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Enumeration constants
• The value labels listed in an enumeration are called
enumeration constants
• Enumeration constants must be valid C++ identifiers; they are
not string or char literals
• Enumeration constants are stored in memory as integers; by
default, the first is assigned the value 0, the second 1, etc.
• Thus the order of the listing determines the relative magnitude
of enumeration constant values; the first is less than the
second, which is less than the third, and so forth
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Specifying different values in enumerations
• By default, the first enumeration constant has the value 0, the
second 1, the third 2, etc.
• The default behavior can be overridden by assigning explicit
values to one or more of the constants
• The next several examples illustrate this option
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Example 1 (enum)
• The following enumeration uses explicit assignment to specify
values for the symbols used in the Roman numeral system:
enum RomanNum { I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M =
1000};
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Example 2 (enum)
• The following enumeration type creates constants that
stand for the months of the year:
enum MonthType {JAN=1, FEB, MAR, APR, MAY, JUN, JUL,
AUG, SEP, OCT, NOV, DEC};
• Only the first constant’s value is specified; since it is 1,
the second is 2, the third is 3, and so on until the last
(DEC) with the value 12
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Using enumerated types
• “Enumerations only create new data types”;
types” to actually store
and use values of the the new types, you must declare
variables
• Variables of each enum type can hold only those values
specified by the enumeration
• For example, with the MonthType enumeration, you could
declare variables and assign them values like the following:
MonthType thisMonth = APR;
MonthType nextMonth = MAY;
MonthType birthMonth = nextMonth;
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Operations on enumerations
• Since enumerations are not built-in data types, only some of the
most common operations can be performed using variables of
these types
• The allowable operations include:
– logical comparison using the relational operators (<, >, <=, >=, ==, !=)
– simple arithmetic (but not arithmetic/assignment operations like ++ or --)
– enumerations can be parameters to, and/or return values from, functions
– enumerations can be used as switch expressions and/or case labels in
switches – example on next slide
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
MonthType thisMonth;
…
switch ( thisMonth ) // using enum type switch expression
{
case JAN :
case FEB :
case MAR : cout << “Winter quarter” ;
break ;
case APR :
case MAY :
case JUN : cout << “Spring quarter” ;
break ;
case JUL :
case AUG :
case SEP : cout << “Summer quarter” ;
break ;
case OCT :
case NOV :
case DEC : cout << “Fall quarter” ;
}
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Incrementing enum variables using type
cast mechanism
• The operators ++ and -- are not available for use with enum-
type variables, as previously noted
• However, enum-type variables can appear in mixed-type
expressions with, for example, integers
• This provides a mechanism for increment/decrement of
enumeration type variables
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Using enum type Control Variable with for Loop
MonthType month ;
for (month = JAN ; month <= DEC ; month = MonthType (month + 1 ) )
{ // uses type cast to increment
.
.
.
}
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Simple arithmetic with enumeration constants
• Previously, we defined an enumeration of the symbols used in the Roman numeral
system
• We will use this enumeration to illustrate arithmetic with enums, and see another
example of type casting
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Example
#include <iostream.h>
#include <stdlib.h>
enum RomanNum {I=1, V=5, X=10, L=50, C=100, M=1000};
int main()
{
cout << "Welcome to the world of Roman numerals!" << endl;
int num = (int)(M + C + L + X + V + I);
cout << "MCLXVI=" << num << endl;
num = (int)((L-X) + (V-I));
cout << "XLIV=" << num << endl;
system("PAUSE");
return 0;
}
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Enumerated types and I/O
• The insertion (<<) and extraction (>>) operators are not defined
for enum-type variables
• To perform input or output operations on user-defined types,
you must provide your own functions
• How will you do it? Any Suggestions?
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Typedef
• Definition:– a typedef is a way of renaming a type
• E.g.,
typedef struct motor Motor;
Motor m, n;
Motor *p, r[25];
Motor function(const Motor m; …);
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
typedef
• typedef may be used to rename any type
– Convenience in naming
– Clarifies purpose of the type
– Cleaner, more readable code
• E.g.,
– typedef char *String;
• E.g.,
– typedef int size_t;
– typedef long int32;
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Unions
• A union is like a struct, but only one of its members
is stored, not all
• I.e., a single variable may hold different types at different times
• Storage is enough to hold largest member
• Members are overlaid on top of each other
• E.g.,
union {
int ival;
float fval;
char *sval;
} u;
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Unions
• It is programmer’s responsibility to keep track of which
type is stored in a union at any given time!
• E.g.,
struct taggedItem {
enum {iType, fType, cType} tag;
union {
int ival;
float fval;
char *sval;
} u;
};
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Unions
• It is programmer’s responsibility to keep track of which
type is stored in a union at any given time!
• E.g.,
struct taggedItem {
enum {iType, fType, cType} tag;
Members of struct are:–
union {
int ival;
enum tag;
float fval; union u;
char *sval;
} u;
Value of tag says which
};
member of u to use
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
Unions
• unions are used much less frequently than structs —
mostly
• in the inner details of operating system
• in device drivers
• in embedded systems where you have to access
registers defined by the hardware
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi
Lecture 02: Structures CS 112: Object-Oriented Programming
References
• Book Code: A
Ghulam Ishaq Khan Institute of Engineering Sciences and Technology, Topi