C++ Structs
C. Papachristos
Robotic Workers Lab
University of Nevada, Reno
CS-202
Course Week
CS-202 C. Papachristos
Course , Projects , Labs:
Your 2nd Project will be announced today Thursday 1/30.
1st Project Deadline was this Wednesday 1/29.
Monday | Tuesday | Wednesday | Thursday | Friday | | Sunday |
|
|
| Lab (8 Sections) |
| | |
| CLASS | PASS Session | CLASS |
| | |
PASS Session | | Project DEADLINE | NEW Project | PASS Session | | PASS Session |
Today’s Topics
CS-202 C. Papachristos
C++ Structs
Structs and Arrays
Structs and Functions
C++ Structs
CS-202 C. Papachristos
Description
A “Structure” is a collection of related data items, possibly of different types.
A struct is heterogeneous:
An array is homogeneous:
vs
C++ Structs
CS-202 C. Papachristos
Description
A “Structure” is a collection of related data items, possibly of different types.
A struct is heterogeneous in that it can be composed of data of different types.
In contrast, an array is homogeneous since it can contain only data of the same type.
0 1 2 … 98 99
C++ Structs
CS-202 C. Papachristos
Description
Structures are used to hold data that belong together.
Examples:
In database applications, structures are called records.
C++ Structs
CS-202 C. Papachristos
Members
Struct Members (or Fields):
Versatility:
Struct Members can be of different types:
C++ Structs
CS-202 C. Papachristos
Members
Naming – Resolution:
Versatility:
Complex data structures can be formed by defining arrays of structs.
0 1 2 … 98 99
C++ Structs
CS-202 C. Papachristos
Type Declaration
struct <struct-type> {
<type> <identifier_list>;
<type> <identifier_list>;
...
} ;
Example:
struct Date {
int day;
int month;
int year;
} ;
struct Date {
int day, month, year;
int hours, minutes, seconds;
long microseconds;
} ;
or
C++ Structs
CS-202 C. Papachristos
Type Declaration
Examples:
struct StudentInfo {
int id;
int age;
char gender;
double gpa;
};
struct StudentGrade {
char name[9];
char course[9];
int lab[5];
int homework[3];
int exam[2];
};
The StudentInfo structure has 4 members of different types.
The StudentGrade structure has 5 members of different array types.
C++ Structs
CS-202 C. Papachristos
Type Declaration
Examples:
struct BankAccount {
char name[15];
int acountNo[10];
double balance;
Date birthday;
};
struct StudentRecord {
char name[9];
int id;
char dept[4];
char gender;
};
The BankAccount structure has simple, array and struct types as members.
The StudentRecord structure has 4 members.
C++ Structs
CS-202 C. Papachristos
Variable Declaration
Declaration of a variable of struct type:
struct <struct-type> {
<type> <identifier_list>;
...
} ;
Declaration of a new variable of that type:
<struct-type> <identifier_list>;
Example:
StudentRecord student1, student2;
struct StudentRecord {
char name[9];
int id;
char dept[4];
char gender;
};
C++ Structs
CS-202 C. Papachristos
Variable Declaration
Example:
StudentRecord student1, student2;
(struct)StudentRecord
struct StudentRecord {
char name[9];
int id;
char dept[4];
char gender;
};
StudentRecord
name
id
dept
gender
student1
name
id
dept
gender
student2
name
id
dept
gender
C++ Structs
CS-202 C. Papachristos
Member Access
The Dot (.) Pointer-to-Member Operator:
Used to provide struct type member access.
<struct-variable>.<member_name>;
Example:
student1 . name
student1 . id
student1 . dept
student1 . gender
struct StudentRecord {
char name[9];
int id;
char dept[4];
char gender;
};
Member Access
Example:
strcpy(student1.name, "John Doe");� student1.id = 123;� strcpy(student1.dept, "CSE");� student1.gender = 'M';� cout << "The student is ";� switch (student1.gender){� case 'F': cout << "Ms. "; break;� case 'M': cout << "Mr. "; break;� }� cout << student1.name << endl;
C++ Structs
CS-202 C. Papachristos
student1
name
id
dept
gender
Member Access
Example:
strcpy(student1.name, "John Doe");� student1.id = 123;� strcpy(student1.dept, "CSE");� student1.gender = 'M';� cout << "The student is ";� switch (student1.gender){� case 'F': cout << "Ms. "; break;� case 'M': cout << "Mr. "; break;� }� cout << student1.name << endl;
C++ Structs
CS-202 C. Papachristos
student1
John Doe
Member Access
Example:
strcpy(student1.name, "John Doe");� student1.id = 123;� strcpy(student1.dept, "CSE");� student1.gender = 'M';� cout << "The student is ";� switch (student1.gender){� case 'F': cout << "Ms. "; break;� case 'M': cout << "Mr. "; break;� }� cout << student1.name << endl;
C++ Structs
CS-202 C. Papachristos
student1
John Doe
123
Member Access
Example:
strcpy(student1.name, "John Doe");� student1.id = 123;� strcpy(student1.dept, "CSE");� student1.gender = 'M';� cout << "The student is ";� switch (student1.gender){� case 'F': cout << "Ms. "; break;� case 'M': cout << "Mr. "; break;� }� cout << student1.name << endl;
C++ Structs
CS-202 C. Papachristos
student1
John Doe
123
CSE
Member Access
Example:
strcpy(student1.name, "John Doe");� student1.id = 123;� strcpy(student1.dept, "CSE");� student1.gender = 'M';� cout << "The student is ";� switch (student1.gender){� case 'F': cout << "Ms. "; break;� case 'M': cout << "Mr. "; break;� }� cout << student1.name << endl;
C++ Structs
CS-202 C. Papachristos
student1
John Doe
123
CSE
‘M’
Member Access
Example:
strcpy(student1.name, "John Doe");� student1.id = 123;� strcpy(student1.dept, "CSE");� student1.gender = 'M';� cout << "The student is ";� switch (student1.gender){� case 'F': cout << "Ms. "; break;� case 'M': cout << "Mr. "; break;� }� cout << student1.name << endl;
C++ Structs
CS-202 C. Papachristos
Output:
The student is Mr. John Doe
C++ Structs
CS-202 C. Papachristos
Initialization
StudentRecord student1 = {"John Doe", 123, "CSE", 'M'};
Compromised maintainability.
struct StudentRecord{
char name[9];
int id;
char dept[4];
char gender;
};
C++ Structs
CS-202 C. Papachristos
Initialization
StudentRecord student1 = {"John Doe", 123, "CSE", 'M'};
Compromised maintainability.
Attention! No C99 Inline initialization list with designators (NOT supported in C++):
StudentRecord student1 = {.name="John Doe",.Id=123,.dept="CSE",.gender='M'};
StudentRecord student1 = {.name="John Doe",123,"CSE",'M'};
StudentRecord student1 = {.dept="CSE",‘M’,.name="John Doe",.id=123};
(Note: C++20 reintroduces the concept, under stricter rules …)
struct StudentRecord{
char name[9];
int id;
char dept[4];
char gender;
};
C++ Structs
CS-202 C. Papachristos
Initialization
StudentRecord student1 = {"John Doe", 123, "CSE", 'M'};
Compromised maintainability.
struct StudentRecord{
char name[9];
int id;
char dept[4];
char gender;
};
struct StudentRecord{
char name[5];
int id;
char dept[3];
char gender;
};
Potential Problems due to change in struct declaration!
C++ Structs
CS-202 C. Papachristos
Assignment
The values contained in one struct type variable can be assigned to another variable of the same struct type.
Example:
strcpy(student1.name, "John Doe");� student1.id = 123;� strcpy(student1.dept, "CSE");� student1.gender = 'M';�� StudentRecord student2 = student1;
student1
John Doe
123
CSE
'M'
student2
John Doe
123
CSE
'M'
C++ Structs
CS-202 C. Papachristos
Nested Structures
A struct type can be a member of another struct.
Example:
struct Point { � double x, y;� };
Point p;� � struct Line {� Point p1, p2;� };
Line l;
�
struct Triangle { � Point p1, p2, p3;�};
Triangle t;
(p.x, p.y)
(l.p1.x, l.p1.y)
(l.p2.x, l.p2.y)
(t.p2.x, t.p2.y)
(t.p1.x, t.p1.y)
(t.p3.x, t.p3.y)
C++ Structs
CS-202 C. Papachristos
Nested Structures
A struct type can be a member of another struct.
Example:
struct Line {� Point p1, p2;� };
Line l1;
Line
Point
x
y
Point
x
y
l1
p2
x
y
p1
x
y
Type Definition
Variable Creation
C++ Structs
CS-202 C. Papachristos
Nested Structures
A struct type can be a member of another struct.
Example:
struct StudentRecord {
char name[15];
int id;
char dept[5];
char gender;
StudentRecord emergContact;
};
NO
struct StudentRecord {
char name[15];
int id;
char dept[5];
char gender;
StudentRecord * emergContact;
};
YES !
Pointer of self-referencing type is allowed
C++ Structs
CS-202 C. Papachristos
Nested Structures
A struct type can be a member of another struct.
Example:
Point p;� Line l;
Triangle t;
p.x = 4.0;
p.y = 11.0;
(4.0, 11.0)
(2.0, 7.0)
(9.0, 8.0)
(6.0, 5.0)
(2.0, 0.0)
(8.0, 3.0)
Literals-based Initialization of every primitive data member
C++ Structs
CS-202 C. Papachristos
Nested Structures
A struct type can be a member of another struct.
Example:
Point p;� Line l;
Triangle t;
l.p1.x = 2.0;
l.p1.y = 7.0;
l.p2.x = 9.0;
l.p2.y = 8.0;
(4.0, 11.0)
(2.0, 7.0)
(9.0, 8.0)
(6.0, 5.0)
(2.0, 0.0)
(8.0, 3.0)
Literals-based Initialization of every primitive data member
C++ Structs
CS-202 C. Papachristos
Nested Structures
A struct type can be a member of another struct.
Example:
Point p;� Line l;
Triangle t;
t.p1.x = 6.0;
t.p1.y = 5.0;
t.p2.x = 8.0;
t.p2.y = 3.0;
t.p3.x = 2.0;
t.p3.y = 0.0;
(4.0, 11.0)
(2.0, 7.0)
(9.0, 8.0)
(6.0, 5.0)
(2.0, 0.0)
(8.0, 3.0)
Literals-based Initialization of every primitive data member
C++ Structs
CS-202 C. Papachristos
Nested Structures
A struct type can be a member of another struct.
Example:
Point p;� Line l;
p.x = 2.00;
p.y = 7.00;
l.p1 = p;
p.x = 9.00;
p.y = 8.00;
l.p2 = p;
(p.x, p.y)
(l.p1.x, l.p1.y)
(l.p2.x, l.p2.y)
(t.p2.x, t.p2.y)
(t.p1.x, t.p1.y)
(t.p3.x, t.p3.y)
Modification and Assignment to each struct data member
(Data-Copy)
C++ Structs
CS-202 C. Papachristos
Arrays of Structs
Arrays are homogeneous (one data type):
0 1 2 … 98 99
0 1 2 … 98 99
C++ Structs
CS-202 C. Papachristos
Arrays of Structs
Arrays are homogeneous (one data type):
0 1 2 … 98 99
struct Point { � double x, y;�};
Point point_array[100];
point
x
y
point
x
y
point
x
y
point
x
y
point
x
y
C++ Structs
CS-202 C. Papachristos
Arrays of Structs
All aforementioned operations take place as usual:�
StudentRecord classRecords[100];� �
0 1 2 … 98 99
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
Declaration
C++ Structs
CS-202 C. Papachristos
Arrays of Structs
All aforementioned operations take place as usual:�
StudentRecord classRecords[100];� strcpy(classRecords[98].name,"John Doe");� classRecords[98].id = 123;� strcpy(classRecords[98].dept,"CSE");� classRecords[98].gender = 'M';�
0 1 2 … 98 99
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
???
John Doe
123
CSE
‘M’
John Doe
123
CSE
‘M’
Indexing & Member-Access
C++ Structs
CS-202 C. Papachristos
Arrays of Structs
All aforementioned operations take place as usual:�
StudentRecord classRecords[100];� strcpy(classRecords[98].name,"John Doe");� classRecords[98].id = 123;� strcpy(classRecords[98].dept,"CSE");� classRecords[98].gender = 'M';� classRecords[0] = classRecords[98];
0 1 2 … 98 99
John Doe
123
CSE
‘M’
???
???
???
???
???
???
???
???
???
???
???
???
John Doe
123
CSE
‘M’
John Doe
123
CSE
‘M’
Indexing & Assignment
C++ Structs
CS-202 C. Papachristos
Struct Arrays in Structs
Remember: Arrays can be struct members
struct Point { � double x, y;� };
struct Square { � Point p[4];� };
Square s;
(s.p[0].x, s.p[0].y)
(s.p[1].x, s.p[1].y)
(s.p[3].x, s.p[3].y)
(s.p[2].x, s.p[2].y)
0 1 2 3
p[0]
x
y
p[1]
x
y
p[2]
x
y
p[3]
x
y
C++ Structs
CS-202 C. Papachristos
Structs and Functions
Supported type for Function Parameters can be struct:
struct Point{ double x, y; };
double points_distance(Point p1, Point p2){� return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y);� }
Point p1, p2;
double p12_distance = points_distance(p1, p2);
Data-Copy operation
// need declaration before any mention
// of Point can be made in the program
C++ Structs
CS-202 C. Papachristos
Structs and Functions
Supported type for Function Parameters can be struct &:
struct Point{ double x, y; };
void shift_point_upright(Point & p){� p.x += 1.0;
p.y -= 1.0;� }
Point p;
shift_point_upright(p);
No Data-Copy
Modifies struct members
// need declaration before any mention
// of Point can be made in the program
C++ Structs
CS-202 C. Papachristos
Structs and Functions
Supported type for Function Parameters can be struct const &:
struct Point{ double x, y; };
bool is_point_inbounds(const Point & p){� return p.x>=0 && p.x<NUM_COLS && p.y>=0 && p.x<NUM_ROWS;
}
Point p;
bool p_inbounds = is_point_inbounds(p);
No Data-Copy
// need declaration before any mention
// of Point can be made in the program
C++ Structs
CS-202 C. Papachristos
Structs and Functions
Supported type for Function Parameters can be struct &:
void set_point_inbounds(Point & p){
if (p.x<0) p.x=0; else if (p.x>=NUM_COLS) p.x=NUM_COLS-1;� if (p.y<0) p.y=0; else if (p.y>=NUM_ROWS) p.y=NUM_ROWS-1;
}
void set_point_inbounds(const Point & p){
if (p.x<0) p.x=0; else if (p.x>=NUM_COLS) p.x=NUM_COLS-1;� if (p.y<0) p.y=0; else if (p.y>=NUM_ROWS) p.y=NUM_ROWS-1;
}
const-Reference will not allow mutation
C++ Structs
CS-202 C. Papachristos
Structs and Functions
Supported type for Function Parameters can be struct *:
struct Point{ double x, y; };
void shift_point_upright(Point * p){� (*p).x += 1.0;
(*p).y -= 1.0;� }
Point p;
Point * p_Pt = &p;
shift_point_upright(p_Pt);
Dereferencing to access Value-Pointed-By
Modifies struct members
// need declaration before any mention
// of Point can be made in the program
C++ Structs
CS-202 C. Papachristos
Structs and Functions
Supported type for Function Parameters can be struct []/*:
struct Point{ double x, y; };
void shift_points_downleft(Point * p_arr, int sz){
for (int i=0; i<sz; ++i){� p_arr[i].x -= 1.0;
p_arr[i].y += 1.0;
}� }
Point points_array[100];
shift_points_downleft(points_array, 100);
Modifies struct members
Parameter similarly as:
Point p_arr[]
// need declaration before any mention
// of Point can be made in the program
C++ Structs
CS-202 C. Papachristos
Structs and Functions
Supported return type for Functions can be struct:
struct Point{ double x, y; };
Point mirror_point(const Point & p_in){
Point p_out;� p_out.x = -p_in.x;
p_out.y = -p_in.y;
return p_out;� }
Point p1;
Point p1_mirrored = mirror_point(p1);
Local variable
Point p_out
Data-Copy (assignment)
Point p1_mirrored =
Lifetime?
// need declaration before any mention
// of Point can be made in the program
CS-202 C. Papachristos
Procedural
Focused on the question: “What should the program do next?” Structure program by:
Large amount of data and/or tasks makes projects/programs unmaintainable.
Object-Oriented (OO)
Package-up self-sufficient modular pieces of code.
The world is made up of interacting objects.
Pack away details into boxes (objects) keep them in mind in their abstract form.
Focus on (numerous) interactions.
A collection of Objects
A hierarchy of functions
Remember: Procedural vs Object-Oriented
Remember: Procedural vs Object-Oriented
CS-202 C. Papachristos
The ATM Machine paradigm
struct Date {
int day;
int month;
int year;
};
struct BankAccount {
char name[15];
int acountNo[10];
double balance;
Date birthday;
};
Remember: Classes
CS-202 C. Papachristos
Class
C++ Classes are very similar to C Structs, in that they both include user-defined sets of data items, which collectively describe some entity such as a Student, a Book, an Airplane, or a data construct such as a String, a ComplexNumber, etc…
Bank Account
account number
owner’s name
balance
interest rate
more?
deposit money
withdraw money
check balance
transfer money
more?
Operations
(behaviors)
Type
Attributes (state)
String
sequence of characters
encoding
more?
compute length
concatenate
test for equality
more?
C++ Structs
CS-202 C. Papachristos
Structs in C++
structs encapsulate related data.
(later: Class members by default are private – internally accessible for a specific Object from own methods, i.e. functions)
When to use a struct (for now) :
C++ Structs
CS-202 C. Papachristos
Structs in C++
structs encapsulate related data.
(later: Class members by default are private – internally accessible for a specific Object from own methods, i.e. functions)
When to use a struct (for now) :
Data sanity checking might be necessary!
struct Date {
int month;
int day;
int year;
};
Date bDay{2, 29, 2015};
Not a leap year!
C++ Structs
CS-202 C. Papachristos
Structs in C++
structs can have methods (i.e. functions).
structs can have: (– Note: like Classes do)
C++ Structs
CS-202 C. Papachristos
Struct Methods / Constructors / etc. in C++
struct Date {
int month, day, year;
Date(int m_month, int m_day, int m_year) :
month(m_month), day(m_day), year(m_year){
if (month<=0) month = 1;
if (day<=0) day = 1;
if (year<1985) year = 1985;
fixLeapDate();
}
void fixLeapDate(){
if (year ... && month ... && day ...){
day = ...;
}
}
};
Date bday(2, 29, 2015);
Not a leap year!
C++ Structs
CS-202 C. Papachristos
Struct Methods / Constructors / etc. in C++
struct Date {
int month, day, year;
Date(int m_month, int m_day, int m_year) :
month(m_month), day(m_day), year(m_year){
if (month<=0) month = 1;
if (day<=0) day = 1;
if (year<1985) year = 1985;
fixLeapDate();
}
void fixLeapDate(){
if (year ... && month ... && day ...){
day = ...;
}
}
};
Date bday(2, 29, 2015);
Not a leap year!
C++ Structs
CS-202 C. Papachristos
Struct Methods / Constructors / etc. in C++
struct Date {
int month, day, year;
Date(int m_month, int m_day, int m_year) :
month(m_month), day(m_day), year(m_year){
if (month<=0) month = 1;
if (day<=0) day = 1;
if (year<1985) year = 1985;
fixLeapDate();
}
void fixLeapDate(){
if (year ... && month ... && day ...){
day = ...;
}
}
};
Date bday(2, 29, 2015);
Not a leap year!
C++ Structs
CS-202 C. Papachristos
Struct Methods / Constructors / etc. in C++
Calling Member Methods (i.e. Member Functions)
struct Date {
int month, day, year;
Date(int m_month, int m_day, int m_year) :
month(m_month), day(m_day), year(m_year){ ... }
bool isLeapYear(){ ... return ... ; }
};
Date bday(2, 29, 2015);
bool leap_year = bDay . isLeapYear();
C++ Structs
CS-202 C. Papachristos
By the way … (OO in C)
typedef struct student_t Student;
struct student_t
{
char name[15];
int id;
Student * emergencyContact;
void (*ConstructStudent)();
Student * (*AddEmergContact)(Student *);
};
void construct_student() { ... }
Student * add_emerg_contact(Student *self) { ... }
typedef required
C++ Structs
CS-202 C. Papachristos
By the way … (OO in C)
typedef struct student_t Student;
struct student_t
{
char name[15];
int id;
Student * emergencyContact;
void (*ConstructStudent)();
Student * (*AddEmergContact)(Student *);
};
void construct_student() { ... }
Student * add_emerg_contact(Student *self) { ... }
void* (or worse) members required for�Constructors and Member Methods
By the way … (OO in C)
typedef struct student_t Student;
struct student_t
{
char name[15];
int id;
Student * emergencyContact;
void (*ConstructStudent)();
Student * (*AddEmergContact)(Student *);
};
void construct_student() { ... }
Student * add_emerg_contact(Student *self) { ... }
C++ Structs
CS-202 C. Papachristos
External Function Definitions required
C++ Structs
CS-202 C. Papachristos
By the way … (OO in C)
Did you know?
struct student_t
{ ...
void (*ConstructStudent)();
Student * (*AddEmergContact)(Student *);
};
void construct_student() { ... }
Student * add_emerg_contact(Student *self) { ... }
int main()
{
Student student_a;
student_a.ConstructStudent = &construct_student;
student_a.ConstructStudent();
}
Function Binding of members to external functions required !
C++ Structs
CS-202 C. Papachristos
By the way … (OO in C)
Thankfully C++ is much more Versatile, Expressive than that !
struct Student
{ ...
Student(); // constructor declaration
void AddEmergContact(Student *); // member method declaration
};
void Student::Student() { ... } // constructor definition
void Student::AddEmergContact(Student * other) { ... } // member method definition
int main()
{
Student student_a; // implicit Student() call
Student student_b; // implicit Student() call
student_a.AddEmergContact(&student_b); // direct method call by object
}
Time for Questions !
CS-202
CS-202 C. Papachristos