// you’re reading...

C++ Glossary

Structures

Sometimes it is useful to have a collection of values of different types and to treat the collection as a single item

  • For example, consider a bank certificate of deposit, which is often called a CD
    • A CD is a bank account that does not allow withdrawals for a specified number of months
    • A CD naturally has three pieces of data associated with it:
      • The account balance
      •  The interest rate for the account
      •  The term, which is the number of months until maturity
    • The first two items can be represented
      • As values of type double
    • The number of months can be represented
      • As a value of type int



(A-1) shows the definition of a structure called

  • CDAccountV1 that can be used for this kind of account
    • (The V1 stands for version 1. We will define an improved version later in this page.)



Example of (A-1)

// strctfirst.cpp -- program to demonstrate the CDAccountV1 structure type
#include <iostream>
using namespace std;
 
// structure for a bank certificate of deposit:
struct CDAccountV1
{
    double balance;
    double interestRate;
    int term; // months until maturity
};
 
void getData(CDAccountV1& theAccount);
// postcondition: theAccount.balance, theAccount.interestRate, and 
// theAccount.term have been given values that the user entered at the keyboard
 
int main( )
{
    CDAccountV1 account;
    getData(account);
 
    double rateFraction, interest;
    rateFraction = account.interestRate/100.0;
    interest = account.balance*(rateFraction*(account.term/12.0));
    account.balance = account.balance + interest;
 
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);
    cout << "When your CD matures in " 
         << account.term << " months,\n"
         << "it will have a balance of $" 
         << account.balance << endl;
 
    return 0;
}
 
// uses iostream:
void getData(CDAccountV1& theAccount)
{
    cout << "Enter account balance: $";
    cin >> theAccount.balance;
    cout << "Enter account interest rate: ";
    cin >> theAccount.interestRate;
    cout << "Enter the number of months until maturity: ";
    cin >> theAccount.term;
}



Here is the output from the program in (A-1):

Output




Structure Types



The structure definition in (A-1)

  • Is as follows (A-2):



Example of (A-2)

struct CDAccountV1
{
	double balance;
	double interestRate;
	int term; // months until maturity
};



The keyword struct

  • Announces that this is a structure type definition



The identifier CDAccountV1

  • Is the name of the structure type, which is known as the structure tag
    • The structure tag can be any legal identifier that is not a keyword
      • Although this is not required by the C++ language, structure tags are usually spelled starting with an uppercase letter



The identifiers declared inside the braces, {}

  • Are called member names



As illustrated in (A-2), a structure type definition ends

  • With a closing brace and a semicolon



A structure definition

  • Is usually placed outside any function definition
    • (In the same way that globally defined constant declarations are placed outside all function definitions.)



The structure type

  • Is then a global definition that is available to all the code that follows the structure definition



Once a structure type definition has been given

  • The structure type can be used just like the predefined types int, char, and so forth



Note that in (A-1) the structure type CDAccountV1

  • Is used to declare a variable in the function main
    • And then it is used as the name of the parameter type for the function getData



A structure variable

  • Can hold values just like any other variable can



A structure value

  • Is a collection of smaller values called member values



There is one member value for each member name declared in the structure definition

  • For example, a value of the type CDAccountV1
    • Is a collection of three member values, two of type double and one of type int



The member values that together make up the structure value

  • Are stored in member variables, which we discuss next



Each structure type specifies a list of member names

  • In (A-1) the structure CDAccountV1 has three member names:
    • balance
    • interestRate
    • term
  • Each of these member names can be used to pick out one smaller variable that is a part of the larger structure variable
    • These smaller variables are called member variables



Member variables

  • Are specified by giving the name of the structure variable followed by a dot and then the member name
    • For example, if account is a structure variable of type CDAccountV1 (as declared in(A-1)), then the structure variable account has the following three member variables:
      • account.balance
      • account.interestRate
      • account.term
    • The first two member variables are of type double, and the last is of type int
    • As illustrated in (A-1), these member variables can be used just like any other variables of those types
      • For example, the following line from the program in (A-1) will add the value contained in the member variable account.balance and the value contained in the ordinary variable interest and will then place the result in the member variable account.balance (A-3):



Example of (A-3)

account.balance = account.balance + interest;



Two or more structure types may use the same member names

  • For example, it is perfectly legal to have the following two type definitions in the same program (A-4)
    • This coincidence of names will produce no problems



Example of (A-4)

struct FertilizerStock
{
	double quantity;
	double nitrogenContent;
};
 
struct CropYield
{
	int quantity;
	double size;
};



For example, if you declare the following two structure variables (A-5):

  • Then the quantity of Super Grow fertilizer is stored in the member variable superGrow.quantity
    • And the quantity of apples produced is stored in the member variable apples.quantity
      • The dot operator and the structure variable specify which quantity is meant in each instance



Example of (A-5)

FertilizerStock superGrow;
CropYield apples;



A structure value can be viewed as a collection of member values

  • A structure value can also be viewed as a single (complex) value (that just happens to be made up of member values)



Since a structure value can be viewed as a single value

  • Structure values and structure variables can be used in the same ways that you use simple values and simple variables of the predefined types such as int
    • In particular, you can assign structure values using the equal sign



For example, if apples and oranges are structure variables of the type CropYield defined earlier, then the following is perfectly legal (A-6):

  • The previous assignment statement is equivalent to (A-7)



Example of (A-6)

apples = oranges;



Example of (A-7)

apples.quantity = oranges.quantity;
apples.size = oranges.size;




Forgetting a Semicolon in a Structure Definition



When you add the final brace,}, to a structure definition, it feels like the structure definition is finished, but it is not

  • You must also place a semicolon after that final brace
    • There is a reason for this, even though the reason is a feature that we will have no occasion to use
  • A structure definition is more than a definition
    • It can also be used to declare structure variables
      • You are allowed to list structure variable names between that final brace and that final semicolon
        • For example, the following defines a structure called WeatherData and declares two structure variables, dataPoint1 and dataPoint2, both of type WeatherData (A-8):



Example of (A-8)

struct WeatherData
{
	double temperature;
	double windVelocity;
} dataPoint1, dataPoint2;




Structures as Function Arguments



A function can have

  • Call-by-value parameters of a structure type or call-by-reference parameters of a structure type, or both
    • The program in (A-1), for example, includes a function named getData that has a call-by-reference parameter with the structure type CDAccountV1



A structure type can also be the type for the value returned by a function

  • For example, the following defines a function that takes one argument of type CDAccountV1 and returns a different structure of type CDAccountV1 (A-9)
    • The structure returned will have the same balance and term as the argument, but will pay double the interest rate that the argument pays



Example of (A-9)

CDAccountV1 doubleInterest(CDAccountV1 oldAccount)
{
	CDAccountV1 temp;
	temp = oldAccount;
	temp.interestRate = 2*oldAccount.interestRate;
	return temp;
}



(A-9) notice the local variable temp of type CDAccountV1; temp is used to build up a complete structure value of the desired kind

  • Which is then returned by the function



If myAccount is a variable of type CDAccountV1 that has been given values for its member variables

  • Then the following will give yourAccount values for an account with double the interest rate of myAccount (A-10):



Example of (A-10)

CDAccountV1 yourAccount;
yourAccount = doubleInterest(myAccount);




Use Hierarchical Structures



Sometimes it makes sense to have structures whose members are themselves smaller structures

  • For example, a structure type called PersonInfo
    • That can be used to store a person’s height, weight, and birth date can be defined as follows (A-11):



Example of (A-11)

struct Date
{
	int month;
	int day;
	int year;
};
 
struct PersonInfo
{
	double height; // in inches
	int weight; // in pounds
	Date birthday;
};



A structure variable of type PersonInfo is declared in the usual way (A-12):


Example of (A-12)

PersonInfo person1;



If the structure variable person1 has had its value set to record a person’s birth date

  • Then the year the person was born can be output to the screen as follows (A-13):



Example of (A-13)

cout << person1.birthday.year;



The way to read such expressions is left to right, and very carefully

  • Starting at the left end, person1 is a structure variable of type PersonInfo
    • To obtain the member variable with the name birthday, you use the dot operator as follows (A-14):
      • This member variable is itself a structure variable of type Date
        • Thus, this member variable itself has member variables
          • A member variable of the structure variable person1.birthday is obtained by adding a dot and the member variable name, such as year, which produces the expression person1.birthday.year shown above (A-13)



Example of (A-14)

person1.birthday



In (A-15) we have rewritten the class for a certificate of deposit from (A-1)

  • This new version has a member variable of the structure type Date that holds the date of maturity
    • We have also replaced the single balance member variable with two new member variables giving the initial balance and the balance at maturity



Example of (A-15)

// strctsec.cpp -- program to demonstrate the CDAccount structure type
#include <iostream>
using namespace std;
 
struct Date
{
    int month;
    int day;
    int year;
};
 
// improved structure for a bank certificate of deposit:
struct CDAccount
{
    double initialBalance;
    double interestRate;
    int term; // months until maturity
    Date maturity; // date when CD matures
    double balanceAtMaturity;
};
 
void getCDData(CDAccount& theAccount);
// postcondition: theAccount.initialBalance, theAccount.interestRate, 
// theAccount.term, and theAccount.maturity 
// have been given values that the user entered at the keyboard
 
void getDate(Date& theDate);
// postcondition: theDate.month, theDate.day, and theDate.year 
// have been given values that the user entered at the keyboard
 
int main( )
{
    CDAccount account;
    cout << "Enter account data on the day account was opened:\n";
    getCDData(account);
 
    double rateFraction, interest;
    rateFraction = account.interestRate/100.0;
    interest = account.initialBalance*(rateFraction*(account.term/12.0));
    account.balanceAtMaturity = account.initialBalance + interest;
 
    cout.setf(ios::fixed);
    cout.setf(ios::showpoint);
    cout.precision(2);
    cout << "When the CD matured on " 
         << account.maturity.month << "-" << account.maturity.day
         << "-" << account.maturity.year << endl
         << "it had a balance of $" 
         << account.balanceAtMaturity << endl;
    return 0;
}
 
// uses iostream:
void getCDData(CDAccount& theAccount)
{
    cout << "Enter account initial balance: $";
    cin >> theAccount.initialBalance;
    cout << "Enter account interest rate: ";
    cin >> theAccount.interestRate;
    cout << "Enter the number of months until maturity: ";
    cin >> theAccount.term;
    cout << "Enter the maturity date:\n";
    getDate(theAccount.maturity);
}
 
// uses iostream:
void getDate(Date& theDate)
{
    cout << "Enter month: ";
    cin >> theDate.month;
    cout << "Enter day: ";
    cin >> theDate.day;
    cout << "Enter year: ";
    cin >> theDate.year;
}



Here is the output from the program in (A-15): 

Output Second




Initializing Structures



You can initialize a structure at the time that it is declared

  • To give a structure variable a value, follow it by an equal sign and a list of the member values enclosed in braces



For example, the following definition of a structure type for a date was given in the previous subsection (A-16):

  • Once the type Date is defined, you can declare and initialize a structure variable called dueDate as follows (A-17):
    • The initializing values must be given in the order that corresponds to the order of member variables in the structure type definition
      • In this example (A-17):
        • dueDate.month receives the first initializing value of 12
        • dueDate.day receives the second value of 31
        • dueDate.year receives the third value of 2003



It is an error if there are more initializer values than struct members

  • If there are fewer initializer values than struct members, the provided values are used to initialize data members, in order
    • Each data member without an initializer is initialized to a zero value of an appropriate type for the variable



Example of (A-16)

struct Date
{
	int month;
	int day;
	int year;
};



Example of (A-17)

Date dueDate = {12, 31, 2003};


Discussion

No comments for “Structures”

Post a comment