CIS 22B - Notes for Wed Oct 25

Announcements and Reminders

Topics

Structs

A struct is 
  • an abstract data type
  • a composite type
  • a user-defined type
  • almost the exact same thing as a class in C++ (but we'll get to that later)
Structs contain members, accessible through the . (dot) operator, and maybe through the -> (arrow) operator.

Example:

struct something        // struct declaration
{
   int a;               // members
   float b;
   char c;
};

...

something var;          // you can also say "struct something var;"

// assign the members of the something variable (object)
var.a = 19;
var.b = 3.14;
var.c = 'x';

cout << var.a << ' ' << var.b << ' ' << var.c;    // prints 19 3.14 x
...

something* ps;         // ps is a pointer to something
ps = &var;             // assign the address of a struct variable to a pointer

cout << (*ps).a;       // prints 19
cout << ps->a;         // prints 19

struct initialization

Arrays of structs

Structs with arrays


Nested structs

Example - Assignment 3 using structs

The tm struct

Example

Binary File I/O with structs (this topic is optional)

  • What is a binary file?
  • Two new I/O functions
istream::read
ostream::write
Example

What about a struct with strings in it?    Don't jump to conclusions