CSC 306 Introduction to Programming with C++

Creating and Using Structures

Chapter 6


Objectives

Important Definitions


Structures

Most of the data types we have been working with represent a single value such as a char, an integer or a double number. The type "C-string" is different because it is made up of smaller pieces, namely the characters. C-strings are therefore an example of a compound type. Depending on what you are doing, you may want to treat a compound type as a single thing, or you may want to access its parts. This ambiguity is useful as we saw in dealing with C-strings. You can also create your own compound values in C++, using two mechanisms: structures and classes. We will first learn about structures.

As a simple example of a compound structure, consider the concept of a point in the x-y plane. A point is made up as a pair of two numbers that represent the x and y coordinates that can be treated collectively. In mathematical notation, points are often written in parentheses, with a comma separating the coordinates.

A natural way to represent a point in C++ is with two doubles, and we can represent that using a struct definition:

// Here we define a new "type" called point.
struct point { 
  double x, y;  //point has two member variables.
};
A structure is a programmer-defined data type that consists of a collection of data variables grouped together and treated as a single object. The above structure example contains the member variables x and y, where a member variable is one of the named pieces of data that make up a structure. Struct definitions are included outside of any function definition and like identifiers must be defined before they are used. Also like variables, struct definitions typically are at the beginning of a program.
WARNING It probably seems odd to put a semi-colon after the "}", but that is how a struct definition ends. A very common syntax error is to leave off the semi-colon at the end of a structure definition.
Once the new structure is defined, we can declare variables of this type, such as the myPoint example below, and assign the member variables values in much the same way we assign values of int or float variables.

point myPoint;   // declare a variable of type point
myPoint.x = 3.5; // assign the x member variable the value 3.5
myPoint.y = 4.2; // assign the y member variable the value 4.2
The dot notation used here is similar to the syntax for invoking a member function, as in cout.precision( ), but x and y are member variables. After all three statements execute, the following diagram shows the contents of myPoint:

myPoint
x: 3.5
y: 4.2

Member Variables

With the exception that member variables are part of a structure, they behave very much like any other simple variable types. Suppose you have the following code fragment:
struct point {
  double x;
  double y;
};

int main( ) {
  double z, x;
  point myPoint;

  myPoint.x = 3.5; // These two are the same as the statements above
  myPoint.y = 4.2;

  z = myPoint.x;   // z would have the value 3.5 after this statement 
  x = myPoint.x;   // x here is a different variable from myPoint.x
}
The statement "z = myPoint.x" goes to the object named myPoint, find the member variable x, and assign the value in that member variable to z. A similar operation occurs for the last statement. Note that local variable x and the member variable myPoint.x are different; the dot notation uniquely determines which variable is referred to at a point in time. You can also use member variables in cout or mathematical operations, such as:

// The first statement outputs the string: myPoint = (3.5, 4.2)
// The second statement adds 10 to what is in myPoint.x
// The last statement outputs the new value in myPoint.x: new myPoint.x = 13.5
cout << "myPoint = (" << myPoint.x << ", " << myPoint.y << ")\n"; 

myPoint.x = myPoint.x + 10;

cout << "new myPoint.x = " << myPoint.x << endl;

Initializing Structures

Many of the operators we have been using on other types, such as mathematical operators ( +, %, etc.) and comparison operators (==, >, etc.), do not work on structures. However, the assignment operator does work on a structure in two ways: to initialize its member variables or to copy the values of its member variables to another. You can initialize the values of a structure's member variables by using the following format:

structure_type identifier = { init_member1, init_member2, ... };
The values in the { } braces get assigned to the member variables of the structure in the order they occur. If a structure has 20 member variables and the initialization statement only has 10, the first 10 variables will be assigned their initial value, but the remaining 10 will not. Consider the myPoint structure. The following shows the contents of that structure after various initialization has been done:

point myPoint = { 3.5, 4.2 }; point myPoint = { 3.5 };
myPoint
x: 3.5
y: 4.2
myPoint
x: 3.5
y: 0

Unfortunately, this syntax can be used only in an initialization and not in an assignment statement. The following is illegal.

point mypoint;
mypoint = { 3.5, 4.2 };       // WRONG !!
It is legal to intialize a structure by giving it another structure. The following code fragment initializes p1 with the values (3.5, 4.2), then initializes p2 to have the same values for the member variables as p1. Therefore, the output would be "(3.5, 4.2)", as expected:

point p1 = { 3.5, 4.2 };
point p2 = p1;
cout << "(" << p2.x << ", " <<  p2.y << ")";

Structures as Function Parameters

Structures can be passed into function as both call by value or with call by reference parameters:
  1. Call by Value Example
    The following code fragment takes a point structure and outputs the coordinates:

    void printPoint( point p ) {
      cout << "(" << p.x << ", " << p.y << ")";
    }
    
    Note that no matter the name of the point structure outside the function, it is called p locally in printPoint(...). Suppose the argument to the function was myPoint defined and initialized above, it will output the string (3.5, 4.2)".

    Changing the values of the structure p will not change the variable myPoint. If inside printPoint(...) there was the statement "p.x = 10.0", the structures in the program will be:
    p
    x: 10.0
    y: 4.2
    myPoint
    x: 3.5
    y: 4.2
    Note that although the x member function in p changed, the one for myPoint did not.

  2. Call by Reference
    Recall that sometimes, you want to have a function change the value of variables that are passed in as parameters --- for this, you would use call by reference. For example, suppose you want to reflect a point around the 45-degree line. This can be done by swapping the two coordinates (i.e. x and y switch values), as defined by the following reflect(...) function:
    void reflect( point& p ) {  // Note the ampersand before p
      double temp = p.x;
      p.x = p.y;
      p.y = temp;
    }
    
    The following code fragment and description demonstrate what the function does:
    Code Fragment Description
    point myPoint
    printPoint( myPoint );
    reflect( myPoint );
    printPoint( myPoint );
    
    myPoint has the values: x=3.5 y=4.2
    output:(3.5, 4.2) 
    swap the x and y values
    output: (4.2, 3.5) 
    

The Boolean Type

A boolean expression is one that evaluates to either true or false. A data type that we have not previously discussed, but that will prove useful in this assignment is the type bool. It is a basic data type like int, but instead of storing integers or doubles or characters, variables of type bool store either the value true or the value false. The words true and false are reserved C++ words.

An example variable declaration and assignment of type bool is:


	bool testvariable;
	testvariable = true;

Assignment Specifics

This assignment must be completed individually.

Create a program in a source file called YourLastName_306A12.cpp that

  1. uses the point structure as described above.

  2. asks the user to type in the coordinates for two points:
    Define a function that gets from the user the coordinate of a single point and have your program call it twice to get the two points.

  3. determines whether or not the points are equal:
    Define a function that takes as input two point structures passed in as call by value and returns true is the two points are the same and false otherwise.

  4. calculates the distance between the two points:
    Define a call by value function that takes two points as input and returns the distance between the points as a double number. Recall that distance between (x1, y1) and (x2, y2) is given by the distance formula

    WARNING: Do NOT name this function "distance" as it will cause conflicts with a built-in C++ distance(...) function that works differently.

  5. outputs (1) the two points, (2) whether or not they are equal, and (3) what the distance between the two are:
    You are welcome to use the printPoint(...) function that was given above to display the point coordinates.

Be sure to do the following:

When you are finished writing and testing your assignment, drop your source code file into the CSC306_A12 dropbox on the Academic server.


Back to Introduction to Computer Programming with C++ Homepage