Title: Introduction to Classes
1Introduction to Classes
2Procedural and Object-Oriented Programming
- 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 abstract data types (ADTs) that
encapsulate the data and its functions
3Limitations of Procedural Programming
- If the data structures change, many functions
must also be changed - Data and functions are separate entities
- As programs become larger and more complex, the
separation of a programs data and the code that
operates on the data can lead to problems - difficult to understand and maintain
- difficult to modify and extend
- easy to break
4Object Oriented Programming
- OOP programming is centered on creating objects
- An object is a software entity that contains both
data and procedures - Conceptually, it is a self-contained unit
consisting of attributes (data) and procedures
(methods or functions) - The data is known as the objects attributes
- The procedures that an object performs are called
member methods or functions
5Classes and Objects
- A class is like a blueprint (not real) and
objects are like houses built from the blueprint
(real things) - An object is an instance of a class
6More on Objects
- encapsulation combining data and code into a
single object - data hiding restricting access to the data of an
object from code that is outside the object - public interface members of an object that are
available outside of the object. - This allows the object to provide access to some
data and functions without sharing its internal
details and design, and provides some protection
from data corruption - What are the public interfaces of a car? What do
they hide?
7Class and Object Example
Ranch house object
Each house has windows, doors, floors, etc. How
many of each and what type differentiate each
object
House class
Town house object
Two family house object
8Class and Object Example
Savings Account object
What might these three accounts have in
common? How might they differ?
Bank Account
Checking Account object
Mutual Fund object
9Introduction to Classes
- Objects are created from a class
- A class has no memory allocated to it while an
object does - The first letter of the class is capitalized to
show it is not a variable name - Format
- class ClassName
-
- declaration
- declaration
-
10Class Example
Attributes
Methods/ Functions
11Access Specifiers
- Used to control access to members of the class
- public can be accessed by functions outside of
the class - private can only be called by or accessed by
functions that are members of the class - Attributes are generally made private so they can
not be directly accessed outside of the object - Private attributes can only be accessed through
the public functions
12Class Example
Private Members
Public Members
In order for an outside program to set the
private attribute width of an object, the
function setWidth() must be invoked
13More on Access Specifiers
- Can be listed in any order in a class
- Can appear multiple times in a class
- Best to group all private declarations in one
spot and all public declarations in their own
spot - If not specified, the default is private
- It is best to explicitly declare attributes as
private even though its not necessary
14Using const With Member Functions
- const appearing after the parentheses in a member
function declaration specifies that the function
will not change any data in the calling object. - This can act as a check on the function so that
if code was inserted to change an attribute, the
compiler will generate an error
15Defining a Member Function
- When defining a member function
- Put function prototype in class declaration
- Code for the function is written outside the
class - Define function using class name and scope
resolution operator () -
-
void RectanglesetWidth(double w) width w int RectanglegetLength()const return length
int RectanglegetArea()const return lengthwidth int RectanglegetArea()const return lengthwidth
16Accessors and Mutators
- Mutator a member function that stores a value in
a private member variable, or changes its value
in some way (setLength and setWidth) - Accessor function that retrieves a value from a
private member variable. - Accessors do not change an object's data, so they
should be marked const (getLength and getWidth)
17Defining an Instance of a Class
- An object is an instance of a class
- Classname objectname
- Defined as (instantiated as)
- Rectangle r
- Access members using dot operator
- r.setWidth(5.2)cout ltlt r.getWidth()
- int x r.getArea()
- Compiler error if attempt to access private
member using dot operator outside the class - Inside the class functions, the member attributes
are directly accessible
18(No Transcript)
19(No Transcript)
20A Rectangle object named box is created, the
values in length and width are garbage
In lines 83 and 84, width and length are assigned
real values
21(No Transcript)
22Multiple Objects of the same Class
- You can define more than one object of the same
class within a program - Each object gets its own name or is part of an
array - You precede the function name with the name of
the name of the object to uniquely identify it
(see 13-2) -
- Rectangle kitchen // To hold kitchen
dimensions - Rectangle bedroom // To hold bedroom
dimensions -
- // Get the kitchen dimensions.
- cout ltlt "What is the kitchen's length? "
- cin gtgt number //
Get the length - kitchen.setLength(number) //
Store in kitchen object - cout ltlt "What is the kitchen's width? "
- cin gtgt number //
Get the width - kitchen.setWidth(number) //
Store in kitchen object - // Get the bedroom dimensions.
- cout ltlt "What is the bedroom's length? "
- cin gtgt number //
Get the length - bedroom.setLength(number) //
Store in bedroom object
23Avoiding Stale Data
- An objects state is the data that is stored in
the objects attributes at any given moment - Some data is the result of a calculation.
- In the Rectangle class the area of a rectangle is
calculated by length width - If we were to use an area variable here in the
Rectangle class, its value would be dependent on
the length and the width. - If we change length or width without updating
area, then area would become stale. - To avoid stale data, it is best to calculate the
value of that data within a member function
rather than store it in a variable.
24Pointer to an Object
- Can define a pointer to an object
- Rectangle rPtr //Rectangle pointer
- Rectangle myRectangle //Rectangle Object
- rPtr myRectangle
- Can access public members via pointer using the
-gt operator - rPtr otherRectangle
- rPtr-gtsetLength(12.5)
- cout ltlt rPtr-gtgetLenght() ltlt endl
25Dynamically Allocating an Object
- We can also use a pointer to dynamically allocate
an object.
26Why Have Private Members?
- Making data members private provides data
protection - Data can be accessed only through public
functions - Public functions define the classs public
interface
27Why Have Private Members?
Code outside the class must use the class's
public member functions to interact with the
object. Can provide validation.
Void Rectangle setWidth(double w) if (wgt0)
width w else coutltltInvalid width\n
exit(EXIT_FAILURE) Parameter is tested
and validated before being assigned
28Separating Specification from Implementation
- Place class declaration in a header file that
serves as the class specification file. Name the
file ClassName.h, for example, Rectangle.h - Place member function definitions in the
implementation file ClassName.cpp, for example,
Rectangle.cpp 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 member function definitions
29Separating Specification from Implementation
- Provides flexibility
- A class can be given to another programmer
without sharing the source code by providing the
compiled object file for the classs
implementation - The other programmer inserts the necessary
include directive into his program, compiles it
and links it with your classs object file - When a classs member functions must be modified,
it is only necessary to modify the implementation
file and recompile it into a new object file - Programs that use the class dont have to be
completely recompiled, just linked with the new
object file
30Rectangle.h
This directive tells the preprocessor to see if a
constant named RECTANGLE_H has not been
previously created with a define directive
- // Specification file for the Rectangle class.
- ifndef RECTANGLE_H
- define RECTANGLE_H
- // Rectangle class declaration.
- class Rectangle
-
- private
- double width
- double length
- public
- void setWidth(double)
- void setLength(double)
- double getWidth() const
- double getLength() const
- double getArea() const
-
- endif
The first included line defines the RECTANGLE_H
constant. If this file is included again, the
include guard will skip its contents
If the RECTANGLE_H constant has not been defined,
these lines are included in the program.
Otherwise, these lines are not included in the
program
31Rectangle.h
- Preprocessor directives ifndef and endif
- include guard prevents the header file from
accidentally being included more than once by an
include in a main - Could have two includes, where second include
specifies a .h files that the first include
already specified - ifndef if not defined
32Rectangle.cpp
- The implementation file contains the member
functions of the class - The first line is include Rectangle.h
- The filename is enclosed in double quotation
marks this indicates that the file is in the
current project directory - The angled brackets lt gt are used to include files
that are found in the compilers include file
directory this is where all of the standard C
header files are located - The remaining code consists of the member
functions - In Codeblocks or Dev C you can create a
project with 3 separate files and then build and
run the main program - On UNIX you can compile all the cpp file on one
line and then run the resulting executable - g RectangleMain.cpp Rectangle.cpp o
RectangleRun - You can also compile Rectangle cpp into an object
file (Rectangle.o) once it is set using g -c
Rectangle.cpp and then include it with the main
on the full compile - g -c RectangleMain.cpp Rectangle.o o
RectangleRun
33Rectangle Specification Implementation
- // Rectangle.h
- ifndef RECTANGLE_H
- define RECTANGLE_H
- // Rectangle class declaration.
- class Rectangle
-
- private
- double width
- double length
- public
- void setWidth(double)
- void setLength(double)
- double getWidth() const
- double getLength() const
- double getArea() const
-
//RectangleMain.cpp // This program uses the
Rectangle class, which is declared in // the
Rectangle.h file. The member Rectangle class's
member // functions are defined in the
Rectangle.cpp file. This program // should be
compiled with those files in a project. include
ltiostreamgt include "Rectangle.h" // Needed for
Rectangle class using namespace std int
main() Rectangle box // Define an
instance of the Rectangle class double
rectWidth // Local variable for width double
rectLength // Local variable for length //
Get the rectangle's width and length from the
user. cout ltlt "This program will calculate the
area of a\n" cout ltlt "rectangle. What is the
width? " cin gtgt rectWidth cout ltlt "What
is the length? " cin gtgt rectLength //
Store the width and length of the rectangle //
in the box object. box.setWidth(rectWidth)
box.setLength(rectLength) // Display the
rectangle's data. cout ltlt "Here is the
rectangle's data\n" cout ltlt "Width " ltlt
box.getWidth() ltlt endl cout ltlt "Length " ltlt
box.getLength() ltlt endl cout ltlt "Area " ltlt
box.getArea() ltlt endl return 0
34Rectangle Specification Implementation
// Rectangle.cpp include "Rectangle.h" //
Needed for the Rectangle class include
ltiostreamgt // Needed for cout include
ltcstdlibgt // Needed for the exit
function using namespace std //
//
setWidth sets the value of the member variable
width. //
void RectanglesetWidth(d
ouble w) if (w gt 0) width w
else cout ltlt "Invalid width\n"
exit(EXIT_FAILURE) //
//
setLength sets the value of the member variable
length. //
void RectanglesetLength(d
ouble len) if (len gt 0) length
len else cout ltlt "Invalid
length\n" exit(EXIT_FAILURE)
//
// getWidth returns the value in the
member variable width. //
double
RectanglegetWidth() const return
width //
// getLength returns the
value in the member variable length.
//
double RectanglegetLength()
const return length //
//
getArea returns the product of width times
length. //
double
RectanglegetArea() const return width
length
35Rectangle Specification Implementation
Rectangle.cpp (Implementation file)
Rectangle.h (Specification file)
RectangleMain.cpp (Main Program file)
Rectangle.h is included
Rectangle.h is included
RectangleMain.cpp is compiled
Rectangle.cpp is compiled
Rectangle.obj and RectangleMain.obj are linked
and RectangleRun.exe is created
Rectangle.obj (Object file)
RectangleMain.obj (Object file)
RectangleMain.exe (Executabel file)
36Inline Member Functions
- When a member function is defined in the
declaration of a class, it is called an inline
function - No need to use the scope resolution operator and
class name in the function header - Some member functions can be inline while others
can be in a specification file outside the class
declaration - Inline appropriate for short function bodies
- int getWidth() const return width
37Inline Member Functions
- In order to call a function from a class
specification file, a lot of time consuming
overhead occurs that can add up when a function
is called many times - The functions return address in the program and
the value of the arguments are stored in the
stack - Local variables are created and a location is
reserved for the functions return value - Inline functions are compiled differently than
other functions - Inline expansion the compiler replaces the call
to an inline function with the code of the
function itself eliminating the external function
call overhead - However, because the inline functions code can
appear multiple times the size of the program can
increase which can decrease system performance
when paging is used
38Rectangle Class with Inline Member Functions
1 // Specification file for the Rectangle
class 2 // This version uses some inline member
functions. 3 ifndef RECTANGLE_H 4 define
RECTANGLE_H 5 6 class Rectangle 7 8
private 9 double width10 double
length11 public12 void
setWidth(double)13 void
setLength(double)14 15 double
getWidth() const16 return width
17 18 double getLength()
const19 return length 20
21 double getArea() const22
return width length 23 24 endif
Inline functions
39Constructors
- Member function that is automatically called when
an object is created - Purpose is to initialize an objects attributes
at the time the object is created. This way,
object variables never have invalid values - Constructor function name is class
nameRectangleRectangle(parameters) - In class declaration under public methods
-Rectangle(parameters) - In class specification - Rectangle(parameters)
- Has no return type, not even void
40(No Transcript)
41(No Transcript)
42(No Transcript)
43Default Constructors
- A default constructor is a constructor that takes
no arguments. - If you write a class with no constructor at all,
when the class is compiled C will write a
default constructor for you, one that does
nothing RectangleRectangle() - This is not a wise thing to do as the class
variables will not be initialized properly. Its
best to write a constructor with no arguments and
make default assignments to the class variables - A simple instantiation of a class (with no
arguments) calls the default constructor e.g.,
Rectangle r - recptr new Rectangle creates an object and
executes the deafult constructor - Rectangle recptr does not create an object so
the constructor is not executed.
44Default Constructors
- If you have a non-default constructor without a
default and try to create an object with no
arguments, the code wont compile - The default constructor will only be created if
there are no other constructors. Once there is
one non-default constructor, you must explicitly
create the default constructor if you need it
45Passing Arguments to Constructors
- To create a constructor that takes arguments
- indicate parameters in prototypeRectangle(double
, double) - Use parameters in the definitionRectangleRect
angle(double w, double len) width w
length len - You can pass arguments to the constructor when
you create an object Rectangle r(10, 5)
46Classes with No Default Constructor
- When all of a class's constructors require
arguments, then the class has NO default
constructor. - When this is the case, you must pass the required
arguments to the constructor when creating an
object.
47Pointers and Objects
- To create an object with pointers and call the
member functions, follow the code below - //rectWidth and rectLength are read in
earlier - Rectangle box
- box new Rectangle(rectWidth,rectLength)
- // Display the rectangle's data.
- cout ltlt "Here is the rectangle's data\n"
- cout ltlt "Width " ltlt box-gtgetWidth() ltlt endl
- cout ltlt "Length " ltlt box-gtgetLength() ltlt endl
- cout ltlt "Area " ltlt box-gtgetArea() ltlt endl
48Default Arguments with Constructors
- A default value can be specified in the
constructor header using inline code - class Rectangle
-
- private
- double width
- double length
- public
- Rectangle()
- RectangleRectangle(double w, double
l100) - width w
- length l
-
-
-
- Which is the called in main by Rectangle box
(rectWidth)
49Default Arguments with Constructors
- If not using inline code, then do as follows
- In Rectangle.h
- public
- Rectangle(double, double l100.0)
- In Rectangle.cpp
- RectangleRectangle(double w, double l)
-
- width w
- length l
-
- Which is the called in main by Rectangle box
(rectWidth) - This will automatically substitute 100 for length
- The value of 100 can be overridden by calling
Rectangle box (rectWidth,rectLength) in main
50Destructors
- Member function automatically called when an
object is destroyed - Destructor name is classname, e.g., Rectangle()
- In class specification file include
- RectangleRectangle()
coutltlt"Destructor is running"ltltendl - Has no return type takes no arguments
- Only one destructor per class, i.e., it cannot be
overloaded - If constructor allocates dynamic memory,
destructor should release it
51Destructors
- Including a destructor prototype in Rectangle.h
and function in Rectangle.cpp will cause the
destructor to execute when main is complete - This program will calculate the area of a
- rectangle. What is the width? 23
- What is the length? 12
- Here is the rectangle's data
- Width 23
- Length 12
- Area 276
- Destructor is running
52InventoryItem.h
53InventoryItem.h
54(No Transcript)
55Constructors, Destructors, and Dynamically
Allocated Objects
- When an object is dynamically allocated with the
new operator, its constructor executesRectangle
r new Rectangle(10, 20) - When the object is destroyed, its destructor
executesdelete r
56Overloading Constructors
- A class can have more than one constructor
- Overloaded constructors in a class must have
different parameter lists - Rectangle()Rectangle(double)
- Rectangle(double, double)
57Overloading Constructors
- //
- // Default Constructor
- //
- RectangleRectangle()
-
- width 0
- length0
-
- //
- // Set only the width, length is fixed at 100
- //
- RectangleRectangle(double w)
-
- width w
- length10
-
- //
58From InventoryItem.h
59Only One Default Constructor
and One Destructor
- Do not provide more than one default constructor
for a class in the specification file (.h file)
i.e., one that takes no arguments and one that
has default arguments for all parameters - Square()
- Square(int 0) // will not compile
- If you execute code Square sqr in main, the
compiler wont know which constructor to use
the error message will state that constructor
call is ambiguous - Since a destructor takes no arguments, there can
only be one destructor for a class
60Member Function Overloading
- Non-constructor member functions can also be
overloaded - void setCost(double)
- void setCost(char )
- Must have unique parameter lists as for
constructors - void setcost(double c) costc
- void setcost(char c) costatof(c)
61Using Private Member Functions
- A private member function can only be called by
another member function - It is used for internal processing by the class,
not for use outside of the class - Function is included in the private section of
the class specification file and functions in the
public section can call it
62Using Private Member Functions
- private
- void createDescription(int size, char value)
-
- description new charsize
- strcpy(description,value)
-
- public
- InventoryItem()
-
- createDescription(DEFAULT_SIZE,)
- cost0.0
- units0.0
-
63Arrays of Objects
- Objects can be the elements of an array
InventoryItem inventory40 - Default constructor for object is called for each
object in the array - Must use initializer list to invoke constructor
that takes arguments InventoryItem inventory3
"Hammer", "Wrench", "Pliers" - If the class does not have a default constructor,
you must provide an initializer for each object
in the array
64Arrays of Objects
- If the constructor requires more than one
argument, the initializer must take the form of a
function call - It isn't necessary to call the same constructor
for each object in an array
65Arrays of Objects
- If you dont provide an initializer for all the
objects in an array, the default constructor will
be called for each object that does not have an
initializer. - In this case, for the third object
- InventoryItem inventory3 Hammer,
- InventoryItem(Wrench,8.75,20)
-
66Accessing Objects in an Array
- Objects in an array are referenced using
subscripts - Member functions are referenced using dot
notation inventory2.setUnits(30) - cout ltlt inventory2.getUnits()
67(No Transcript)
68OOP Case Study
- You are a programmer for the Home Software
Company. You have been assigned to develop a
class that models the basic workings of a bank
account. - The class should perform the following tasks
- Save the account balance.
- Save the number of transactions performed on the
account. - Allow deposits to be made to the account.
- Allow withdrawals to be taken from the account.
- Calculate interest for the period.
- Report the current account balance at any time.
69OOP Case Study
- Private Member Variables needed by the class.
Variable Description
balance A double that holds the current account balance.
interestRate A double that holds the interest rate for the period
interest A double that holds the interest earned for the current period.
transactions An integer that holds the current number of transactions
70OOP Case Study - Public Member Functions
Function Description
Constructor Takes arguments to he initially stored in the balance and interestRate members. The default value for the balance is zero and the default value for the interest rate is 0.045.
setInterestRate Takes a double argument which is stored in the interestRate member
makeDeposit Takes a double argument, which is the amount of the deposit. This argument is added to balance.
withdraw Takes a double argument which is the amount of the withdrawal. This value is subtracted from the balance, unless the withdrawal amount is greater than the balance. If this happens, the function reports an error.
calcInterest Takes no arguments. This function calculates the amount of interest for the current period, stores this value in the interest member, and then adds it to the balance member.
getInterestRate Returns the current interest rate (stored in the interestRate member).
getBalance Returns the current balance (stored in the balance member).
getInterest Returns the interest earned for the current period stored in the interest member).
getTransactions Returns the number of transactions for the current period (stored in the transactions member).
71Account.h
- ifndef ACCOUNT_H
- define ACCOUNT_H
- class Account
-
- private
- double balance
- double interestRate
- double interest
- int transactions
- public
- Account(double iRate 0.045, double bal 0)
- balance bal
- interestRate iRate
- interest 0
- transactions 0
- void setInterestRate(double iRate)
- interestRate iRate
void calcInterest()
interest balance interestRate
balance interest double
getInterestRate() const return
interestRate double getBalance() const
return balance double
getInterest() const return interest
int getTransactions() const return
transactions endif
72Account.cpp
- // Implementation file for the Account class.
- include "Account.h"
- bool Accountwithdraw(double amount)
-
- if (balance lt amount)
- return false // Not enough in the account
- else
-
- balance - amount
- transactions
- return true
-
-
73The Unified Modeling Language
- UML stands for Unified Modeling Language.
- The UML provides a set of standard diagrams for
graphically depicting object-oriented systems
74UML Class Diagram
- A UML diagram for a class has three main sections.
75Example A Rectangle Class
class Rectangle private double
width double length public bool
setWidth(double) bool setLength(double)
double getWidth() const double
getLength() const double getArea()
const
76UML Access Specification Notation
- In UML you indicate a private member with a minus
(-) and a public member with a plus().
These member variables are private.
These member functions are public.
77UML Data Type Notation
- To indicate the data type of a member variable,
place a colon followed by the name of the data
type after the name of the variable.
- width double - length double
78UML Function Return Type Notation
- To indicate the data type of a functions
parameter variable, place a colon followed by the
name of the data type after the name of the
variable. - To indicate the data type of a functions return
value, place a colon followed by the name of the
data type after the functions parameter list.
setWidth(w double)
setWidth(w double) void
79The Rectangle Class
80Showing Constructors and Destructors
No return type listed for constructors or
destructors
Constructors
Destructor
81Object Oriented Design
- Joes Automotive Shop service foreign cars and
specializes in servicing cars made by Mercedes,
Porsche and BMW. When a customer brings in a car
to the shop, the manager gets the customers
name, address and telephone number. The manager
then determines the make, model and year of the
car and gives the customer a service quote. The
service quote shows the estimated part charges,
estimated labor charges, sales tax and total
estimated charges.
82Object Oriented Design
- Finding the classes and their responsibilities
- Get a written description of the problem domain
- The problem domain is the set of real-world
objects, parties and major events related to the
problem - This may include
- Physical objects such as vehicles, machines or
products - Any role played by a person, such as a manager,
employer, customer, teacher, student, etc. - The results of a business event such as a
customer order or service quote - Recordkeeping items such as customer histories
and payroll records -
83Object Oriented Design
- Identify all the nouns and noun phrases
- Address, BMW, car, cars, customer, estimated
labor charges, foreign cars, model, name,
Porsche, sales tax, Joes Automotive shop,
telephone number, shop, - They are candidates to become classes, the list
must be refined to include only those classes
necessary to solve the problem - Eliminate duplicate nouns
- Cars/ foreign cars Joes Automotive shop/shop
- Some nouns may not be needed in order to solve
the problem - Shop, manager
- Some nouns might represent objects, not classes
- Porsche. Mercedes, BMW, car
- Some nouns might represent simple values that can
be stored in a variable and do not require a
class. - If the answer to both of the following questions
is NO, then the noun probably represents a value
that can be stored in a simple variable - Would you use a group of related values to
represent the items state? - Are there any obvious actions to be performed by
the item? - Address, estimate labor charges, make model,
name, sales tax, telephone number, year
84Object Oriented Design
- We are left with cars, customers and service
quote as class candidates - Next determine the Classs Responsibilities
- the things the class is responsible for knowing
these are the classs attributes - The actions that the class is responsible for
doing these are the classs member functions
85Object Oriented Design
86OOD Problem Domain Exercise
- The bank offers the following types of accounts
to its customers savings accounts, checking
accounts, and money market accounts. Customers
are allowed to deposit money into an account
(thereby increasing its balance), withdraw money
fruit an account (thereby decreasing its
balance), and earn interest on the account. Each
account has an interest rate. - Assume that you are writing an application that
will calculate the amount of interest earned for
a bank account. - Identify the potential classes in this problem
domain. - Refine the list to include only the necessary
class or classes for this problem. - Identify the responsibilities of the class or
classes.
87OOD Example
- After eliminating duplicates, objects, and
primitive values, the potential classes are
bank, account, and customer - The only class needed for this particular problem
is account. - The account class knows its balance and interest
rate. - The account can calculate interest earned.