Title: Using Structures and Classes
1Using Structures and Classes
Lecture 4
2Objectives
- 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
3Structures
- 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
4Structure 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
names double interestRate int term
5Declare Structure Variable
- With structure type defined, now
declarevariables of this new typeCDAccountV1
account - Just like declaring simple types
- Variable account now of type CDAccountV1
- It contains "member values"
- Each of the struct "parts"
6Accessing 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
7Structure Example Display 6.1 A Structure
Definition (1 of 3)
8Structure Example Display 6.1 A Structure
Definition (2 of 3)
9Structure Example Display 6.1 A Structure
Definition (3 of 3)
Ex4-0-1.cpp Ex4-0-2.cpp
10Structure Pitfall
- Semicolon after structure definition
- MUST existstruct WeatherData double
temperature double windVelocity ? REQUIRED
semicolon! - Required since you "can" declare
structurevariables in this location
11Structure Assignments
- Given structure named CropYield
- Declare two structure variablesCropYield
apples, oranges - Both are variables of "struct type CropYield"
- Simple assignments are legalapples oranges
- Simply copies each member variable from
applesinto member variables from oranges
12Structures 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 definitionsends
structure variable back to caller
13Initializing 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
14Creating Classes with Declaration and
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
15Creating Classes with Declaration and
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
16Encapsulating Class Components
- 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
17Designing 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
18Designing 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 fieldit also possesses access to the
function
19Implementing Member Functions
- After you create a member functions 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
20Dot 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 functiondefinition
comes from
21Student Class That Includes One Function
Definition and Implementation
22Implementing Class Functions
Ex4-0-3.cpp
23Data 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 objects
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
24Data 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
25Data Hiding and Encapsulation
- When you compile the program, you receive error
messages indicating that the fields idNum,
lastName, and gradePointAverage are inaccessible
26Using Public Functions to Alter 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
27Using Public Functions to Alter 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)
28Using Public Functions to Alter 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
29Using Public Functions to Alter 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 Students
gradePointAverage field
30Using 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
31Using 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.
32Using Private Functions
EX4-2.cpp
33Considering Scope When Defining 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
34Considering Scope When Defining Member Functions
In the second function, idNum refers to only the
functions local variable named idNum
35Using 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
36Using 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
37Defining 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
38A Class That Contains a Static AthleticFee 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
39Using Static Functions
Ex4-4.cpp
- In the program, the athleticFee field is public,
which is why you can access it directly, as in
StudentathleticFee 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
40Understanding 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
41Understanding the this Pointer
- One copy of each member function is stored, and
each instance of a class uses the same function
code
42Understanding the this Pointer
Ex4-5.cpp
43Understanding 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 objects 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
44Understanding 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 thisit 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
45Using the this Pointer Explicitly
Ex4-6.cpp
- 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
objects data fields
46Using the Pointer-to-Member Operator
- 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
47Using the Pointer-to-Member Operator
Ex4-7.cpp
48Structures 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
Ex4-8.cpp
49Summary
- 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
50Summary
- 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