1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

50
1 Using Structures and Using Structures and Classes Classes COSC 1557 COSC 1557 C++ Programming C++ Programming Lecture 4

Transcript of 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Page 1: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

11

Using Structures and ClassesUsing Structures and Classes

COSC 1557COSC 1557

C++ ProgrammingC++ Programming

Lecture 4

Page 2: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

22

ObjectivesObjectives

• Structures

• Define a class

• Declaration and implementation

• Public and private access modifiers

• Private functions

• Scope resolution operator with class fields and functions

• Static variables

• Pointer this

Page 3: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

StructuresStructures

• 2nd aggregate data type: struct

• Recall: aggregate meaning "grouping"– Recall array: collection of values of same type– Structure: collection of values of different types

• Treated as a single item, like arrays

• Major difference: Must first "define" struct– Prior to declaring any variables

33

Page 4: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Structure TypesStructure Types

• Define struct globally (typically)

• No memory is allocated– Just a "placeholder" for what our struct

will "look like"

• Definition:struct CDAccountV1 Name of new struct "type"{

double balance; member namesdouble interestRate;int term;

};

44

Page 5: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Declare Structure VariableDeclare Structure Variable

• With structure type defined, now declarevariables of this new type:CDAccountV1 account;– Just like declaring simple types– Variable account now of type CDAccountV1– It contains "member values"

• Each of the struct "parts"

55

Page 6: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Accessing Structure MembersAccessing Structure Members

• Dot Operator to access members– account.balance– account.interestRate– account.term

• Called "member variables"– The "parts" of the structure variable– Different structs can have same name

member variables• No conflicts

6-6-66

Page 7: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Structure Example: Structure Example: Display 6.1 Display 6.1 A Structure Definition (1 of 3)A Structure Definition (1 of 3)

77

Page 8: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Structure Example: Structure Example: Display 6.1 Display 6.1 A Structure Definition (2 of 3)A Structure Definition (2 of 3)

88

Page 9: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Structure Example: Structure Example: Display 6.1 Display 6.1 A Structure Definition (3 of 3)A Structure Definition (3 of 3)

99

Ex4-0-1.cppEx4-0-2.cpp

Page 10: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Structure PitfallStructure Pitfall

• Semicolon after structure definition

– ; MUST exist:struct WeatherData{

double temperature;double windVelocity;

}; REQUIRED semicolon!

– Required since you "can" declare structurevariables in this location

6-6-1010

Page 11: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Structure AssignmentsStructure Assignments

• Given structure named CropYield

• Declare two structure variables:CropYield apples, oranges;

– Both are variables of "struct type CropYield"

– Simple assignments are legal:apples = oranges;

• Simply copies each member variable from applesinto member variables from oranges

6-6-1111

Page 12: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Structures as Function ArgumentsStructures as Function Arguments

• Passed like any simple data type– Pass-by-value– Pass-by-reference– Or combination

• Can also be returned by function– Return-type is structure type– Return statement in function definition

sends structure variable back to caller

6-6-1212

Page 13: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Initializing StructuresInitializing Structures

• Can initialize at declaration– Example:

struct Date{

int month;int day;int year;

};Date dueDate = {12, 31, 2003};

– Declaration provides initial data to all three member variables

6-6-1313

Page 14: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

1414

Creating Classes with Declaration Creating Classes with Declaration and Implementation Sectionsand Implementation Sections

• Classes provide a convenient way to group related data

• The Student class is an abstract data type (ADT)• Student is a type you define, as opposed to types

like char and int that are defined by C++• One advantage of creating the Student class is that

when you create a Student object, you automatically create all the related Student fields

Page 15: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

1515

Creating Classes with Declaration Creating Classes with Declaration and Implementation Sectionsand Implementation Sections

• Another advantage is the ability to pass a Student object into a function, or receive a Student object from a function as a returned value, and automatically pass or receive all the individual fields that each Student contains

• The first step to creating a class involves determining the attributes of an object, and subsequently dealing with the object as a whole

Page 16: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

1616

Encapsulating Class Encapsulating Class ComponentsComponents

• Just as the internal components of a radio are hidden, when you write a program and create a class name for a group of associated variables, you hide, or encapsulate, the individual components

• Sometimes you want to change the state of some components, but often you want to think about the entry as a whole and not concern yourself with the details

Page 17: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

1717

Designing ClassesDesigning Classes

• You can think of the built-in scalar types of C++ as classes

• You do not have to define those classes; the creators of C++ have already done so

• For most object-oriented classes, then, you declare both fields and functions

• You declare a function by writing its prototype, which serves as the interface to the function

Page 18: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

1818

Designing ClassesDesigning Classes

• When you declare a class with a function definition, you then create an object of that class, the object possesses more than access to each field—it also possesses access to the function

Page 19: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

1919

Implementing Implementing MemberMember Functions Functions

• After you create a member function’s prototype, you still must write the actual function

• When you construct a class, you create two parts

– The first part is a declaration section, which contains the class name, variables (attributes), and function prototype

– The second part create is an implementation section, which contains the functions themselves

Page 20: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Dot and Scope Resolution OperatorDot and Scope Resolution Operator

• Used to specify "of what thing" they aremembers

• Dot operator:– Specifies member of particular object

• Scope resolution operator:– Specifies what class the function

definition comes from

6-6-2020

Page 21: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

2121

Student Class That Includes Student Class That Includes One Function Definition One Function Definition

and Implementationand Implementation

Page 22: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

2222

Implementing Class FunctionsImplementing Class Functions

Ex4-0-3.cpp

Page 23: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

2323

Data Hiding and EncapsulationData Hiding and Encapsulation

• Object-oriented programmers strive to make their classes similar to real-world objects, which usually do not provide access to their inner workings; access is available only to the interface

• One technique programmers use to provide more complete object encapsulation is to make object’s data private

• One major asset of object-oriented programming is that the information hiding can be accomplished more completely than it is with the procedures used in procedural programs

Page 24: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

2424

Data Hiding and EncapsulationData Hiding and Encapsulation

• Traditional procedural languages do not allow data to be declared as private; object-oriented languages do

• In C++, data hiding means that you can make data members of a class inaccessible to functions that are not part of that class

• Within a C++ class, you accomplish data encapsulation by making the data private instead of public

Page 25: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

2525

Data Hiding and EncapsulationData Hiding and Encapsulation

• When you compile the program, you receive error messages indicating that the fields idNum, lastName, and gradePointAverage are inaccessible

Page 26: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

2626

Using Public Functions to Using Public Functions to Alter Private DataAlter Private Data

• You gain a major advantage when you make a data field private

• Once you create a class, including writing and debugging all of its member functions, outside functions can never modify or erroneously use the private member data of any object in the class

• When you create and test a class, and store its definition in a file, programs that use the definition can be prevented from using member data incorrectly

Page 27: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

2727

Using Public Functions to Using Public Functions to Alter Private DataAlter Private Data

• If a private member of your Student class, such as idNum, must be a four-digit number, or if you require that the idNumber always be preceded by a pound sign, functions that are not a member of your class can never change those rules (either intentionally or by accident)

Page 28: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

2828

Using Public Functions to Using Public Functions to Alter Private DataAlter Private Data

• To setLastName() function shown in Figure 5-9 is a member of the Student class

• You can determine this because the class header contains the Student class name and the scope resolution operator

Page 29: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

2929

Using Public Functions to Using Public Functions to Alter Private DataAlter Private Data

• When you use the setIdNum() function with an object like aJunior, you are assured that aJunior receives a valid idNum

• Figure 5-11 shows how the setGradePointAverage() function can be written to accept a double argument and assure that the argument is no more than 4.0 before assigning it to any Student’s gradePointAverage field

Page 30: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

3030

Using a Complete ClassUsing a Complete Class

• Figure 5-12 shows the entire Student class, all its member functions, and a short program that uses the class

EX4-1.cpp

Page 31: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

3131

Using Private FunctionsUsing Private Functions

• Not all function are public

• When you think of real-world objects, such as kitchen appliances, there are many public functions you control through an interface: adjusting the temperature, etc.

Page 32: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

3232

Using Private FunctionsUsing Private Functions

EX4-2.cpp

Page 33: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

3333

Considering Scope When Considering Scope When Defining Member FunctionsDefining Member Functions

• There are circumstances when the scope resolution operator is required with a class field name

• Whenever there is a conflict between local and class variable names, you must use the scope resolution operator to achieve the results you want

• The member variable with the same name is hidden unless you use the scope resolution operator

Page 34: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

3434

Considering Scope When Considering Scope When Defining Member FunctionsDefining Member Functions

In the second function, idNum refers to only the function’s local variable named idNum

Page 35: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

3535

Using Static Class MembersUsing Static Class Members

• A C++ object is an instantiation of a class that can contain both data members and methods

• When you create an object, a block of memory is set aside for the data members

• Sometimes every instantiation of a class requires the same value

Page 36: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

3636

Using Static Class MembersUsing Static Class Members

• To avoid a waste, you declare the athletic fee variable as static, meaning that it is shared by all the instances

• A class variable that you declare to be static is the same for all objects that are instantiations of the class

• Static variables are sometimes called class variables because they do not belong to a specific object; they belong to the class

Page 37: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

3737

Defining Static Data MembersDefining Static Data Members

• Because it uses only one memory location, a static data member is defined (given a value) in a single statement outside the class definition

• Most often this statement appears just before the class implementation section

Page 38: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

3838

A Class That Contains a Static A Class That Contains a Static AthleticFee FieldAthleticFee Field

Ex4-3.cpp

•Even though each Student declared in the program has a unique ID number, all Student objects share the athletic fee, which was assigned a value just once

• A static class member exists, even when you have not instantiated any objects of the class

Page 39: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

3939

Using Static FunctionsUsing Static Functions

• In the program, the athleticFee field is public, which is why you can access it directly, as in Student::athleticFee = 139.95;

• If it were private, you would have to use a public function to access the value, as with any other private variable

• You cannot use a static function to access a non-static field because static functions do not receive a pointer to the object that uses the function

• You will use a public static function to display the private static variable

Ex4-4.cpp

Page 40: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

4040

Understanding the this PointerUnderstanding the this Pointer

• When you define a class, you include fields and functions

• If the class has one non-static field and one static field such as the Employee class shown in Figure 5-23, and you then declare two Employee objects, you reserve storage for two versions of the non-static field

• However, you store only one version of the static field that every object can use

• C++ does not store member functions separately for each instance of a class

Page 41: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

4141

Understanding the this PointerUnderstanding the this Pointer

• One copy of each member function is stored, and each instance of a class uses the same function code

Page 42: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

4242

Understanding the this PointerUnderstanding the this PointerEx4-5.cpp

Page 43: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

4343

Understanding the this PointerUnderstanding the this Pointer

• Because only one copy of each function exists, when you call a function, it needs to know which objects to use

• To ensure that the function uses the correct object, you use the object’s name, such as clerk or driver, with the dot operator

• Within the displayValue() function, the address of the object is stored in a special pointer called the this pointer

Page 44: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

4444

Understanding the this PointerUnderstanding the this Pointer

• The this pointer holds the memory address of the current object that is using the function

• That is why it is named this—it refers to “this object” as opposed to any other object

• The this pointer also is passed to member functions when they receive additional, explicitly stated arguments

Page 45: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

4545

Using the this Pointer ExplicitlyUsing the this Pointer Explicitly

• Within any member function, you can prove that the this pointer exists and that it holds the address of the current object

• You do so by using the this pointer to access the object’s data fields

Ex4-6.cpp

Page 46: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

4646

Using the Pointer-to-Member Using the Pointer-to-Member OperatorOperator

• The functions operate by using the C++ pointer-to-member operator, which looks like an arrow and is constructed by a programmer by using a dash followed by a right angle bracket (or greater-than sign)

• Any pointer variable that is declared to point to a class object can be used to access individual fields or functions of that class by using the parentheses and the asterisk

Page 47: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

4747

Using the Pointer-to-Member Using the Pointer-to-Member OperatorOperator

Ex4-7.cpp

Page 48: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

Structures versus ClassesStructures versus Classes

• Structures– Typically all members public– No member functions

• Classes– Typically all data members private– Interface member functions public

• Technically, same– Perceptionally, very different mechanisms

6-6-4848

Ex4-8.cpp

Page 49: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

4949

SummarySummary

• Each class you define is an abstract data type, or a group type with its own fields and functions

• A technique programmers use to provide more complete object encapsulation is to make most objects’ data private

• You can make functions private when you want to hide their use from client programs

• You can use the scope resolution operator with class fields and functions

Page 50: 1 Using Structures and Classes COSC 1557 C++ Programming Lecture 4.

5050

SummarySummary

• When you declare a class variable to be static, only one copy of the variable is stored, no matter how many class objects you instantiate

• When you create a class, one copy of each member function is stored

• Polymorphism is the object-oriented program feature that allows the same operation to be carried out differently, depending on the object