1
DR. (MRS) T-S.M.A. ADJAIDOO
z
05
Classes and
COE 351: Object-Oriented Prgramming
Objects
2
z
Today’s Lesson
Recap of
Theory of Theory of Real-world Implementation
Structs and
Objects Classes implementation in C++
Unions
COE 351: Object-Oriented Prgramming
3
z
Learning Outcomes
1 • To understand the need of classes and
objects
2 • To properly understand how to capture real-
world situations as classes and objects
COE 351: Object-Oriented Prgramming
3 • To create classes and objects in Python
Programming language
4
z
Recap of structs and unions
▪ Recall your previous lessons in C
Programming
▪ What are structures?
▪ When are structures needed?
▪ What are unions?
▪ When are unions needed?
COE 351: Object-Oriented Prgramming
▪ What are the limitations of
structures and unions?
This Photo by Unknown Author is licensed under CC BY-NC
5
z
Theory of Objects
▪ What are OBJECTS?
▪ Objects are the building blocks of
an OO program.
▪ A program that uses OO
technology is basically a collection
of objects messaging each other
COE 351: Object-Oriented Prgramming
▪ Each object consists of some data
and behaviour
6
z
Theory of Objects
Object Data
▪ The data stored within an object represents the state of the object.
▪ In OO programming terminology, this data is called attributes
▪ Let’s illustrate using a school system:
▪ Objects that represent students
▪ Attributes such as name, index number, date of birth, gender etc.
COE 351: Object-Oriented Prgramming
▪ The attributes contain the information that differentiates between the various
objects
7
z
Theory of Objects
Object Data: Examples of student attributes
Name: Felix Arthur Name: Kwadjo Baako
Gender: Male Gender: Male
Date of Birth: 26th October 2001 Date of Birth: 15th April 2002
Student No: 123456 Student No: 678910
COE 351: Object-Oriented Prgramming
Name: Leslie Osman Name: Phoebe Ansah
Gender: Female Gender: Female
Date of Birth: 12th March 2000 Date of Birth: 1st July 2001
Student No: 111213 Student No: 141516
8
z
Theory of Objects
Object Behaviours
▪ The behaviour of an object represents what the object can do.
▪ In procedural languages, the behaviour is defined by procedures,
functions, and subroutines.
▪ In OO programming terminology, these behaviours are contained in
COE 351: Object-Oriented Prgramming
methods, and you invoke a method by sending a message to it.
9
z
Theory of Objects
Object Behaviours Student Object
# Attributes
▪ In our student example, consider that one of Name: Felix Arthur
the behaviours required of a student object is Gender: Male
to set and return the values of the various DateofBirth: 26th October 2001
StudentNo: 123456
attributes.
# Behaviours
▪ Therefore, each attribute would have setName(name)
corresponding methods, such as setGender() getName()
COE 351: Object-Oriented Prgramming
and getGender() etc. setGender(gender)
getGender()
▪ These are often called getters and setters in setDateofBirth(dob)
getDateofBirth()
programming languages setStudentNo(studentno)
getStudentNo()
10
z
Theory of Objects
Object Behaviours
setStudentNo(“123456”)
▪ The following information is all a user
needs to know to effectively use a
methods:
▪ The name of the method Student Object
▪ The parameters passed to the method x = getStudentNo( )
COE 351: Object-Oriented Prgramming
▪ The return type of the method
Class Object
11
z
Theory of Classes
▪ What are classes?
vehicles
▪ A class is a blueprint for an object.
▪ When you instantiate an object,
you use a class as the template
for how the object is built.
▪ An object cannot be instantiated
COE 351: Object-Oriented Prgramming
without a class
Tyre count, window count,
body shape, body colour,
Engine type etc
12
z
Theory of Classes
▪ Let us use an example from Student Date of
Name Gender
No Birth
the relational database world.
26th
Felix
Object 1 123456 Male October
▪ In a database table, the Arthur
2001
definition of the table itself Kwadjo 15th April
Object 2 678910 Male
(fields, description, and data Baako 2002
12th
types used) would be a class Object 3 111213
Leslie
Female March
Osman
(metadata), and the objects 2000
COE 351: Object-Oriented Prgramming
would be the rows of the Phoebe 1st July
Object 4 141516 Female
Ansah 2001
table (data).
Student Class
13
z
Theory of Classes
Cookie Dough
Creating Objects
▪ Classes can be thought of as the Cookie
templates, or cookie cutters, for cutter
objects.
▪ A class is used to create an Class Template
object.
COE 351: Object-Oriented Prgramming
Cookie Cookie
Objects: Cookies 1 2
14
z
Theory of Classes
▪ A class can be thought of as a sort of higher-level data type.
For example, just as we create an integer or a float:
▪ x=5
▪ y = 10.5
▪ We can also create an object by using a predefined class:
▪ myObject = MyClass( )
▪ Remember that each object has its own attributes (data) and behaviours
COE 351: Object-Oriented Prgramming
(functions or routines).
▪ A class defines the attributes and behaviours that all objects created with this
class will possess.
15
z
Real-world Implementation
Identifying classes in the real ▪ For example:
world
▪ Classes are to be a grouping of ▪ “A multiple-choice quiz
conceptually-related state
(attributes/features) and behaviour
program that asks
▪ One popular way to group them is
questions and checks
using grammar the answers are correct”
▪ Noun → Object
COE 351: Object-Oriented Prgramming
▪ Adjective → Attribute
▪ Verb → Method
16
z
Real-world Implementation
Try this on your own:
▪ Identify the possible objects, methods and attributes in this scenario:
▪ A digital library management program which checks-in books, displays them for
users to borrow and also checks-out books
COE 351: Object-Oriented Prgramming
z
C++ Implementation
z
C++ Implementation
z
C++ Implementation
▪ The class smallobj defined in this program contains one data item and two
member functions.
▪ The two member functions provide the only access to the data item from
outside the class.
▪ The first member function sets the data item to a value, and the second
displays the value.
▪ Placing data and functions together into a single entity is a central idea in
object-oriented programming.
z
C++ Implementation
Class
Data
data1
data2
data3
Functions
func1( )
func2( )
func3( )
z
Defining the Class
▪ The definition starts with the keyword class, followed by the class name.
▪ The body of the class is delimited by braces and terminated by a semicolon.
▪ The body of the class contains two keywords: private and public.
▪ Private data or functions can only be accessed from within the class.
▪ Public data or functions are accessible from outside the class.
z
C++ Implementation
z
C++ Implementation
▪ The data items within a class are called data
members (or sometimes member data).
▪ There can be any number of data members in a class.
▪ Member functions are functions that are included
within a class.
z
C++ Implementation
▪ A key feature of object-oriented programming is data hiding.
▪ It means that data is concealed within a class so that it cannot be accessed
mistakenly by functions outside the class.
▪ Data hiding, on the other hand, means hiding data from parts of the
program that don’t need to access it.
▪ One class’s data is hidden from other classes.
▪ Data hiding is designed to protect well-intentioned programmers from
honest mistakes.
z
C++ Implementation
▪ Usually the data within a class is private and the functions are public.
▪ The data is hidden so it will be safe from accidental manipulation, while the
functions that operate on the data are public so they can be accessed from
outside the class.
▪ However, there is no rule that says data must be private and functions
public; in some circumstances you may find you’ll need to use private
functions and public data.
z
Syntax of a class definition
z
Defining Objects
▪ Defining an object is similar to defining a variable of any data type: Space is set
aside for it in memory.
▪ Defining objects in this way means creating them. This is also called
instantiating them.
▪ The term instantiating arises because an instance of the class is created.
▪ An object is an instance (that is, a specific example) of a class. Objects are
sometimes called instance variables.
▪ The first statement in main() smallobj s1, s2; defines two objects called s1 and
s2, of class smallobj.
z
Calling Member Functions
▪ To use a member function, the dot operator connects the object name and
the member function.
▪ The dot operator is also called the class member access operator.
▪ The first call to setdata(), s1.setdata(23); executes the setdata() member
function of the s1 object.
▪ This function sets the variable somedata in object s1 to the value 23.
▪ The second call s2.setdata(12); causes the variable somedata in s2 to be
set to 12.
z
C++ Implementation
z
Messages
▪ Some object-oriented languages refer to calls to member
functions as messages.
▪ Thus the call
s1.showdata();
can be thought of as sending a message to s1 telling it to show
its data.
Implementation
C++
z
31
COE 351: Object-Oriented Prgramming
C++ Implementation
z
32
COE 351: Object-Oriented Prgramming
z
Constructors
▪ Automatic initialization is carried out using a special member
function called a constructor.
▪ A constructor is a member function that is executed
automatically whenever an object is created.
z
C++
Implementation
z
C++
Implementation
z
Destructors
▪ A destructor has the same name as the constructor (which is the same as
the class name) but is preceded by a tilde.
▪ It is called automatically when an object is destroyed.
▪ Like constructors, destructors do not have a return value.
▪ They also take no arguments (the assumption being that there’s only one
way to destroy an object).
▪ The most common use of destructors is to de-allocate memory that was
allocated for the object by the constructor.
z
C++ Implementation
z
Objects as
Function
Arguments
z
C++ Implementation
Distance Function
z
C++ Implementation
Main Function
z
C++ Implementation
▪ add_dist(), that is not defined within the Distance class definition.
▪ It is only declared inside the class, with the statement
void add_dist( Distance, Distance );
▪ This tells the compiler that this function is a member of the class but that it will be
defined outside the class declaration, someplace else in the listing.
▪ The function name, add_dist(), is preceded by the class name, Distance, and a new
symbol—the double colon (::).
▪ This symbol is called the scope resolution operator. It is a way of specifying what
class something is associated with. In this situation, Distance::add_dist() means “the
add_dist() member function of the Distance class.”
z
C++ Implementation
z
The Default Copy Constructor
▪ A no-argument constructor can initialize data members to constant values.
▪ A multi-argument constructor can initialize data members to values passed
as arguments.
▪ Another way to initialize an object is to initialize it with another object of the
same type.
▪ You don’t need to create a special constructor for this; one is already built
into all classes. It’s called the default copy constructor.
▪ It’s a one argument constructor whose argument is an object of the same
class as the constructor.
z
The Default Copy
Constructor
z
The Default Copy Constructor
z
The Default Copy Constructor
▪ dist1 is initialized to the value of 11’-6.25” using the two-argument
constructor.
▪ Two more objects of type Distance, dist2 and dist3 are defined, initializing
both to the value of dist1. These definitions both use the default copy
constructor.
▪ The object dist2 is initialized in the statement
Distance dist2(dist1);
▪ This causes the default copy constructor for the Distance class to perform a
member-by-member copy of dist1 into dist2.
z
Static Class Data
▪ If a data item in a class is declared as static, only one such item is created for the entire
class, no matter how many objects there are.
▪ A static data item is useful when all objects of the same class must share a common item
of information.
▪ A member variable defined as static has characteristics similar to a normal static variable:
▪ It is visible only within the class, but its lifetime is the entire program.
▪ It continues to exist even if there are no objects of the class.
▪ While a normal static variable is used to retain information between calls to a function,
static class member data is used to share information among the objects of a class.
Static Class Data
z
48
COE 351: Object-Oriented Prgramming
Static Class Data
z
49
COE 351: Object-Oriented Prgramming
z
Static Class Data
▪ The class foo in this example has one data item, count, which is type static
int.
▪ The constructor for this class causes count to be incremented.
▪ In main() three objects of class foo are defined.
▪ Since the constructor is called three times, count is incremented three
times.
▪ Another member function, getcount(), returns the value in count.
z
Static Class Data
▪ Here’s the output:
count is 3 ← static data
count is 3
count is 3
z
Static Class Data
▪ If we had used an ordinary automatic variable—as opposed to a
static variable—for count, each constructor would have incremented
its own private copy of count once, and the output would have been
count is 1 ← automatic data
count is 1
count is 1
z
Static Class Data
z
const Member Functions
▪ A const member function guarantees that it will never modify any of its
class’s member data.
▪ A function is made into a constant function by placing the keyword const
after the declaration but before the function body.
▪ If there is a separate function declaration, const must be used in both
declaration and definition.
▪ Member functions that do nothing but acquire data from an object are
obvious candidates for being made const, because they don’t need to
modify any data.
z
Exercise
Imagine a tollbooth at a bridge. Cars passing by the booth are expected to pay a 50 pesewas toll. Mostly
they do, but sometimes a car goes by without paying. The tollbooth keeps track of the number of cars that
have gone by, and of the total amount of money collected.
Model this tollbooth with a class called tollBooth. The two data items are a type unsigned int to hold the total
number of cars, and a type double to hold the total amount of money collected. A constructor initializes both
of these to 0.
A member function called payingCar() increments the car total and adds 0.50 to the cash total.
Another function, called nopayCar(), increments the car total but adds nothing to the cash total.
Finally, a member function called display() displays the two totals. Make appropriate member functions const.
Include a program to test this class. This program should allow the user to push one key to count a paying
car, and another to count a nonpaying car. Pushing the Esc key should cause the program to print out the
total cars and total cash and then exit.
56
Any Questions?
z
The End
Contact: [email protected]
Office: Caesar Building, Room 413
COE 351: Object-Oriented Prgramming