Page 70 - PowerPoint Presentation
P. 70
CAVITE STATE UNIVERSITY
T3 CAMPUS
Department of Information Technology DCIT 25 – Data Structures and Algorithms
the program. Here is a structure that defines a student record consisting of a student number
and grade. The name of this user-defined data types is StudentRecord.
struct StudentRecord {
int studentNumber;
char grade;
};
Declaring a User-Defined Data Type
You declare an instance of a user-defined data types using basically the same
technique that you use to declare a variable. However, you use the name of the structure in
place of the name of the primitive data type in the declaration station.
Let’s say that you want to create an instance of the StudentRecord structure, here’s
the declaration statement that you need to declare in your program.
#include <iostream>
using namespace std;
struct StudentRecord {
int studentNumber;
char grade;
};
void main() {
StudentRecord myStudent;
myStudent.studentNumber = 10;
myStudent.grade = ‘A’;
cout << “Grades: “ << myStudent.studentNumber << “ “ <<
myStudent.grade << endl;
}
The declaration statement tells the computer to reserve memory the size required to
store the StudentRecord user-defined data type and to associate myStudent with that
memory location. The size of a user-defined data type is equal to the sum of the sizes of the
primitive data types declared in the body of the structure.
The size of the StudentRecord user-defined data type is the sum of the sizes of an
integer and char.
Accessing Elements of a User-Defined Data Type
Elements of a data structure are accessed by using the name of the instance of the
structure and the name of the element separated by a dot operator. Let’s say that you want to
assign the grade A to the grade element of the myStudent instance of the StudentRecord
structure. Here’s how you would write the assignment statement:
myStudent.grade = ‘A’ ;
You use elements of a structure the same way you use a variable within your program
except you must reference both the name of the instance and the name of the element in order
to access the element. The combination of instance name and element name is the alias for
the memory location of the element.
User-Defined Data Type and Classes
Structures are used in procedure languages such as C. Object-oriented languages
such as C++ and Java use both structures and classes to group together unlike primitive data
types into a cohesive unit.
Page | 17