Presentation is loading. Please wait.

Presentation is loading. Please wait.

A “User – Defined Data Type”

Similar presentations


Presentation on theme: "A “User – Defined Data Type”"— Presentation transcript:

1 A “User – Defined Data Type”
Creating Structures A “User – Defined Data Type”

2 Structure Concepts Structures use the reserved word struct
Structures are defined just after using namespace std; and before function prototypes

3 Structure Concepts (cont’d)
Structures package related data together Ex. Description, price, quantity might be combined to represent an item in a store Syntax:

4 Structure Concepts (cont’d)
Remember – for all practical purposes a structure is a data type so the structure identifies can not be used as a variable. Variables of the structure data type have to be created Example - name a_name; item an_item;

5 Use of “dot notation” Dot notation is used to identify the data member to be accessed. Example - getline(cin, a_name.first); cout << “price: “<< an_item.price; Data members can be used just like standard variables of the same data type – tot_value = an_item.price * an_item.qoh;

6 Structure Declaration and Initialization
To declare a variable of a structure type and initialize it – a data set has to be used. Braces are used to define the data set. Example - name a_name = {“XX”, “XX”, “XX”}; item block={“cheek”, 5, 45.50}; Let’s say the price of the block increased by 30%. We could now do something like – block.cost = block.cost * 1.3;

7 If we just sold 3 blocks we could – block.qoh = block.qoh – 3;
Another example – We want to print out the data in a_name in the form of last name, first name then middle name – cout << a_name.last<<“, “<<a_name.first <<“ “<<a_name.mi<< endl; So we have packaged data together into a single data unit – a data structure.

8 Now the Huge Advantage Remember the structure variable is a SINGLE value that has several components that can be accessed. Remember that a function can return only a single value which is created (or modified) within the function

9 Assume the following function heading – name make_name( ) This function is going to return a single value of name type – remember that each name variable has 3 parts (refer to slide 3) packaged into a single name

10 So we might define the make_name function below –
name make_name ( ) { name a_name; cout << “First name: “; getline(cin, a_name.first); cout << “Last name: “; getline(cin, a_name.last); cout << “Middle name: “; getline(cin, a_name.mi); return a_name; }//End of name make_name ( )


Download ppt "A “User – Defined Data Type”"

Similar presentations


Ads by Google