Structured Data and Classes Chapter 7 Combining Data
Structured Data and Classes Chapter 7
Combining Data into Structures n n Structure: C++ construct that allows multiple variables to be grouped together Structure Declaration Format: structure name { type 1 field 1; type 2 field 2; … typen fieldn; };
Example struct Declaration struct Student { int student. ID; string name; short year; float gpa; }; structure tag structure members Notice the required ;
struct Declaration Notes n n struct names commonly begin with an uppercase letter Multiple fields of same type can be in a comma-separated list string name, address;
Defining Structure Variables n n struct declaration does not allocate memory or create variables To define variables, use structure tag as type name s 1 Student s 1; student. ID name year gpa
Accessing Structure Members n Use the dot (. ) operator to refer to members of struct variables getline(cin, s 1. name); cin >> s 1. student. ID; s 1. gpa = 3. 75; n Member variables can be used in any manner appropriate for their data type
Displaying struct Members n To display the contents of a struct variable, you must display each field separately, using the dot operator Wrong: cout << s 1; // won’t work! Correct: cout << << s 1. student. ID << endl; s 1. name << endl; s 1. year << endl; s 1. gpa;
Initializing a Structure n Cannot initialize members in the structure declaration, because no memory has been allocated yet struct Student // Illegal { // initialization int student. ID = 1145; string name = “Alex”; short year = 1; float gpa = 2. 95; };
Initializing a Structure n n Structure members are initialized at the time a structure variable is created Can initialize a structure variable’s members with either n n an initialization list a constructor
Using an Initialization List n An initialization list is an ordered set of values, separated by commas and contained in { }, that provides initial values for a set of data members {12, 6, 3} // initialization list // with 3 values
More on Initialization Lists n n Order of list elements matters: First value initializes first data member, second value initializes second data member, etc. Elements of an initialization list can be constants, variables, or expressions {12, W, L/W + 1} // initialization list // with 3 items
Initialization List Example Structure Declaration struct Dimensions { int length, width, height; }; Structure Variable box length 12 width 6 3 height Dimensions box = {12, 6, 3};
Partial Initialization n Can initialize just some members, but cannot skip over members Dimensions box 1 = {12, 6}; //okay Dimensions box 2 = {12, , 3}; //illegal
Problems with Initialization List n n Can’t omit a value for a member without omitting values for all following members Does not work on most modern compilers if the structure contains any string objects n Will, however, work with C-string members
Using a Constructor to Initialize Structure Members n n n A constructor is a special function that can be a member of a structure It is normally written inside the struct declaration Its purpose is to initialize the structure’s data members
Using a Constructor (continued) n n n Unlike most functions, a constructor is not called; instead, it is automatically invoked when a structure variable is created The constructor name must be the same as the structure name (i. e. the struct tag) The constructor must have no return type
A Structure with a Constructor struct Dimensions { int length, width, height; // Constructor Dimensions(int L, int W, int H) {length = L; width = W; height = H; } };
Passing Arguments to a Constructor n n Create a structure variable and follow its name with an argument list Example: Dimensions box 3(12, 6, 3);
Default Arguments n A constructor may be written to have default arguments struct Dimensions { int length, width, height; // Constructor Dimensions(int L=1, int W=1, int H=1) {length = L; width = W; height = H; } };
Examples //Create a box with all dimensions given Dimensions box 4(12, 6, 3); //Create a box using default value 1 for //height Dimensions box 5(12, 6); //Create a box using all default values Dimensions box 6; Omit () when no arguments are used
Nested Structures A structure can have another structure as a member. struct Person. Info { string name, address, city; }; struct Student { int student. ID; Person. Info p. Data; short year; float gpa; };
Members of Nested Structures n Use the dot operator multiple times to dereference fields of nested structures Student s 5; s 5. p. Data. name = "Joanne"; s 5. p. Data. city = "Tulsa";
Structures as Function Arguments n May pass members of struct variables to functions compute. GPA(s 1. gpa); n May pass entire struct variables to functions show. Data(s 5); n Can use reference parameter if function needs to modify contents of structure variable
Notes on Passing Structures n n n Using a value parameter for structure can slow down a program and waste space Using a reference parameter speeds up program, but allows the function to modify data in the structure To save space and time, while protecting structure data that should not be changed, use a const reference parameter void show. Data(const Student &s) // header
Returning a Structure from a Function n Function can return a struct Student get. Stu. Data(); s 1 = get. Stu. Data(); n // prototype // call Function must define a local structure n n for internal use to use with return statement
Returning a Structure Example Student get. Stu. Data() { Student s; // local variable cin >> s. student. ID; cin. ignore(); getline(cin, s. p. Data. name); getline(cin, s. p. Data. address); getline(cin, s. p. Data. city); cin >> s. year; cin >> s. gpa; return s; }
Unions n Similar to a struct, but n n n all members share a single memory location (which saves space) only 1 member of the union can be used at a time Declared using key word union Otherwise the same as struct Variables defined and accessed like struct variables
Example union Declaration union Wage. Info { float hourly. Rate; float annual. Salary; }; union tag union members Notice the required ;
Anonymous Union n A union without a tag: union {. . . }; n n n With no tag you cannot create additional union variables of this type later Allocates memory at declaration time Refer to members directly without dot operator
Anonymous Union Example union { int weight. Lbs; float weight. Oz; }; n
Abstract Data Types n A programmer-created data type that specifies n n n legal values that can be stored operations that can be done on the values The user of an abstract data type does not need to know any implementation details (e. g. , how the data is stored or how the operations on it are carried out)
Abstraction and Data Types n Abstraction: a definition that captures general characteristics without details n n Ex: abstract triangle is a 3 -sided polygon. A specific triangle may be scalene, isosceles, or equilateral Data Type: defines the kind of values that can be stored in a variable and the operations that can be performed on it
Object-Oriented Programming n n Procedural programming focuses on the process/actions that occur in a program Object-Oriented programming is based on the data and the functions that operate on it. Objects are instances of ADTs.
Limitations of Procedural Programming n n Use of global data may allow data corruption Programs are often based on complex function hierarchies n n n difficult to understand maintain difficult to modify and extend easy to break
Object-Oriented Programming Terminology n class: similar to a struct n n n Allows bundling of related variables (member data) and the functions that operate on them (member functions) Describes the properties that all instances of the class will have object: an instance of a class, in the same way that a variable can be an instance of a struct
More Object-Oriented Programming Terminology n n n attributes: member data of a class methods or behaviors: member functions of a class data hiding: restricting access to certain members of an object
Public Interface n Class objects are accessed from outside the class via a public interface n n n This is done by allowing some of the member functions to be called from outside the class Normally all the class’s member variables are accessed only through these “public” functions provides some protection from data corruption
Introduction to Classes n n n A class declaration describes the member variables and member functions that its objects will have It is a pattern for creating objects Class Declaration Format: class. Name { declaration; }; Notice the required ;
Access Specifiers n Used to control access to members of the class. Each member is declared to be either public: can be accessed by functions outside of the class or private: can only be called by or accessed by functions that are members of the class
Class Example Access specifiers class Square { private: int side; public: void set. Side(int s) { side = s; } int get. Side() { return side; } };
More on Access Specifiers n Can be listed in any order in a class n Can appear multiple times in a class n If not specified, the default is private
Introduction to Objects n n An object is an instance of a class Defined like structure variables Square sq 1, sq 2; n Access members using dot operator sq 1. set. Side(5); cout << sq 2. get. Side(); n Compiler error if attempt to access private member using dot operator
Defining Member Functions n n or n Member functions are part of a class declaration Can place entire function definition inside the class declaration Can place just the prototype inside the class declaration and write the function definition after the class
Defining Member Functions Inside the Class Declaration n n Member functions defined inside the class declaration are called inline functions Only very short functions, like the one below, can be inline functions int get. Side() { return side; }
Inline Member Function Example inline functions class Square { private: int side; public: void set. Side(int s) { side = s; } int get. Side() { return side; } };
Defining Member Functions After the Class Declaration n To define a member function after the class declaration n n Put a function prototype in the class declaration In the function definition, precede function name with class name and scope resolution operator (: : ) int Square: : get. Side() { return side; }
Tradeoffs of Inline vs. Regular Member Functions n When a regular function is called, control passes to the called function n n the compiler stores return address of call, allocates memory for local variables, etc. Code for an inline function is copied into the program in place of the call n n larger executable program but no function call overhead, hence faster execution
Design Considerations n n Class should be designed to provide functions to store and retrieve data In general, I/O should be done by functions that use class objects, rather than by class member functions (Exceptions can occur, as with a class designed to display a menu)
More Design Considerations n Separating class declaration, member function definitions, and program that uses the class into separate files is considered good design
Using Separate Files n n n Place class declaration in a header file that serves as the class specification file. Name the file classname. h (for example, Square. h) Place member function definitions in a class implementation file. Name the file classname. cpp (for example, Square. cpp)This file should #include the class specification file. Programs that use the class must #include the class specification file and be compiled and linked with the class implementation file.
Using a Constructor with a Class n As with a structure, a constructor can be used to initialize data members of a class n Must be a public member function n Must be named the same as the class n Must have no return type n Is called automatically when an object of the class is created
The Default Constructor n n Constructors can have any number of parameters, including none A default constructor is one that takes no arguments either due to n No parameters or n All parameters have default values
Default Constructor Example class Square { private: int side; public: Square() { side = 1; } }; Has no parameters // default // constructor // Other member // functions go here
Another Default Constructor Example class Square { private: int side; Has parameter but it has a default value public: Square(int s = 1) // default { side = s; } // constructor }; // Other member // functions go here
Invoking a Constructor n n Invoking a constructor for a class object is done just like invoking a constructor for a structure variable To create an object using the default constructor, use no argument list and no () Square square 1; n To create an object using a constructor that has parameters, include an argument list Square square 1(8);
Overloading Constructors n n A class can have > 1 constructor Overloaded constructors in a class must have different parameter lists Square(); Square(int); n Only one default constructor is allowed
Member Function Overloading n Non-constructor member functions can also be overloaded void set. Side(); void set. Side(int); n Must have unique parameter lists constructors) (as with
Destructors n n n Public member function automatically called when an object is destroyed Destructor name is ~class. Name, e. g. , ~Square Has no return type Takes no arguments Only 1 destructor is allowed per class (i. e. , it cannot be overloaded)
Input Validation Objects can be designed to validate user input n n n to ensure acceptable menu choice to ensure a value is in range of valid values etc.
Using Private Member Functions n n A private member function can only be called by another member function of the same class It is used for internal processing by the class, not for use outside of the class
- Slides: 61