c++ classes in depth
DESCRIPTION
C++ Classes in Depth. Topics. Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects. Objectives. At the completion of this topic, students should be able to:. Design classes for use in a C++ program - PowerPoint PPT PresentationTRANSCRIPT
C++ Classes in Depth
TopicsDesigning Your Own ClassesAttributes and BehaviorsWriting Classes in C++Creating and Using Objects
ObjectivesAt the completion of this topic, students should be able to:
Design classes for use in a C++ programExplain the difference between a class and an objectExplain what attributes and behaviors areExplain the terms encapsulation and data hidingCreate a program that uses a programmer designed class
Let’s review some concepts from CS 1400
Objects are used to model real-world things.You can think of an object as a rather complexvariable that contains multiple chunks of data
Let’s consider an object that represents a time.
Real world objects have attributes
An object’s attributes describe its“state of being”
What things do we normally associate with the state of a time?
seconds minutes
hours am/pm
We hide the data from anyone outsideof the object by making it “private”
A Time object
Joe WageEarner
12356
$12.50
40
The attributes of an object arestored inside the object as
data members.
An “Time” object
The hour valueis stored as an integer
The minute valueis stored as an integer
am or pm isstored as a string
3
35
pm
An object also has behaviors
behaviors define how you interact with the object
What can you do with a time?
Get the hoursset the
hours
Behaviors are expressed as methods thatgive us controlled access to the data.
These are “public” so that we can see them.
An “Time” object
Joe WageEarner
12356
$12.50
40
getH
our (
)
setHour( )
Then we write statements thatsend messages to the objects
An “Time” object named joe
Joe WageEarner
12356
$12.50
40
getH
our (
)
setHour ( )
joe.getHours( );
An Object’s Attributes and Behaviors Should Work Together
this is called cohesion
EncapsulationTime object
getHour( )
hourminute
calling method
we should not allow codeoutside of the object to reach in and change the data directly. Instead, we call methods in theobject to do it for us.
member data is declared as private
member methods are declared as public
The terms public and private are called access modifiers
A Class is a blueprint that a programuses when it creates an object.
A class reserves no space in memory
When an object is created from the classblueprint, memory is reserved to hold the
object’s attributes.
An object is known as an instance of the class.
Each object has it’s own space and data.
A class is said to be an abstraction of thereal world object that we are modeling.
Classes are sometimes calledAbstract Data Types.
We use a UML Class Diagram to documentthe data and methods contained in
our class.
Time
A UML class diagram is usedto describe a class in a very preciseway.
A class diagram is a rectangle.
At the top of the rectangle is theclass name. A line separates theclass name from the rest of thediagram.
Time
- hour: intFollowing the class name we writethe data members of the class. Aline separates the data membersfrom the rest of the diagram.
access modifier:+ public- private
data member name
data type
Time
- hour: int- minute: int
Following the data members, wewrite the member functions.
+ getHour( ): int
access modifier + public - private
method name
parametersreturn type
It is important that class diagrams be drawnprecisely and that they conform to the form
shown in these examples.
In C++ the class definition usually goesinto a separate file called the header file.
It has a file extension of .hmytime.h
class Time{ private: int hour; int minutes; string amOrPm public: Time( ); int getHour( ) const; int getMinutes( ) const; string getAmOrPm( ); void setHour( int n); void setMinutes( int n); void setAmOrPm(string a);};
In C++ the class definition usually goesinto a separate file called the header file.
It has a file extension of .hmytime.h
class Time{ private: int hour; int minutes; string amOrPm public: Time( ); int getHour( ) const; int getMinutes( ) const; string getAmOrPm( ); void setHour( int n); void setMinutes( int n); void setAmOrPm(string a);};
Notice that getter functions (functionsthat do not change the state of theobject) are declared as const functions.
Declaring Member Data
class Time{ private: int hour; int minutes; string amOrPm;
}
Member data is always “private”
Indent each line inside the block
data typevariable name
Declaring Member Data
We call data members of a class “Instance Data”because each instance (object) of the classwill contain its own unique copy of this data.
class Time{ private: int hour; int minutes; string amOrPm;
}
Declaring Member Methods
public class Time{ private: . . . public: Time( ); int getHour( ) const; int getMinutes( ) const; string getAmOrPm( ) const; void setHour( int n); void setMinutes( int n); void setAmOrPm(string a);
Member methods are usually public
return typefunction name parameters
When would you make a method private?
These are calledfunction prototypes
In C++ the code that implements the memberfunctions of the class goes into a related file
with the file extension .cppmytime.cpp
#include “mytime.h” . . .
string Time::getHour( ) const{ return hour;}
void Time::setHour( double n){ hour = n} . . .
always #includethe .h file for
this class
Class name followed by ::
“Setter”Methods
void Time::setHour(int hr) { hour = hr;
}
setters neverreturn anything
they are usually named“set” plus the name of theinstance variable theywill store the value in.
setters always takea parameter
“Getter”Methods
int Time::getHour( ) const { return hour;
}
getters always return something
they are usually named“get” plus the name of theinstance variable theywill return the value of.
getters take no parameters
The const keywordis required to tell thecompiler that the functiondoes not alter the object.
The methods of a class
are the public services or the public interface thatthis class offers to its clients.
Clients are neither aware of nor involved in the implementationdetails of these methods. Clients care what a method does, butnot how it does it.
Static DataEvery instance object has its own copy of all of the instance variables in a class.
What if you want to have all objects of a class share a single instance of a variable? For example, all savingsAccount objects might have the sameinterest rate.
To do this, declare the variable as
private static double interestRate = 0.0725;
Static MethodsA static method can be called without creating an object of the class that it belongs to. Static methods don’t operate on data in an object unless the data itself is declared as static. When you invoke a static method you use the nameof the class instead of an object name.
The this referenceEvery instance object contains a variable named thisthat is a pointer to itself.
The keyword is often used when you want to explicitly name a variable as a data member of this object. For example, in the Time class we havediscussed is a method
void setHour( int hr) { hour = hr; }
The this referenceUsing the this reference we could write:
void setHour( int hr) { this->hour = hr; }
More to come on pointers and “this” in a few weeks.
Creating Objects
class Time{ private: int hour; int minute; . . .
}
Class definitionTime startTime;
this statement takes the Time classdefinition and uses it to createthe object “startTime”.
When creating the object, storage is allocated for the each of the data members defined in the class.
startTimehourminute
Constructors
When an object is created, the data members inside theobject need to be initialized. Otherwise, they take on theResidual values of the bits in the memory that the object occupies.
You can use a constructor to initialize data members in a classto values passed in to the constructor as parameters.
Constructors
Time::Time( ) { hour = 0; minutes = 0;}
No return typeis mentioned
A constructor has thesame name as the class.
You only need to write a non-parameterized constructor if youneed one, If you do not write a non-parameterized constructor, the compiler creates one for you. It takes no parameters and itsbody is empty, so it does not initialize anything.
Constructors
Time::Time(int hr, int min ) { hour = hr; minutes = min;}
You can also write aparameterized
constructor.
If you write a parameterized constructor, you must also write a non-parameterized one. The non-parameterizedconstructor is called the default constructor.
Sending Messages to Objects
startTime.setHour(8);
message
objectname
. method name
parameter
startTimehourminute
startTime.setHour(8);
message
parameter
startTimehourminute
void setHour(int hr){ hour = hr;}
This statement send the setHourmessage to the object named startTime.
As the method executes, the value ofthe parameter hr is stored in the instance variable hour.
The code that creates objects and sends messages to them is typically written in main( ) in what we call adriver. This code is saved in a separate .cpp file.
driver.cpp
#include <iostream>#include “time.h”using namespace std;
int main( ){ Time newTime; . . .
myTime.setHour(3); . . .}
always #includethe .h file for any class used in main
Designing a Class
Classes model real world things, like …
* an employee * a student * a car * a rectangle * a circle * a bowling team . . .
* A RectangleWhat words would you useto describe a rectangle, i.e.what are its attributes?
These become data members of the class.
it’s widthit’s heightit’s color
Draw a Class DiagramRectangle
- width: int- height: int
* A RectangleWhat can I do with/to a Rectangle?
These become member functions of the class.
create onechange it’s height or widthcalculate it’s area
Draw a Class DiagramRectangle
- width: int- height: int
- color: string
+ Rectangle(:int, :int, :string)+ setHeight(:int)+ setWidth(:int)+ getArea( ): int
Create the .h File
class Rectangle{ private: int height; int width; string color; public: Rectangle ( ); Rectangle (int, int, string); void setWidth( int ); void setHeight( int ); int getArea( ) const;};
For brevity I have not included the function prologues
Idea of aRectangle
List• attributes• operations
ClassDiagram
.h File
Design Summary
The following code createsa Rectangle object using anon-parameterized constructor.
Rectangle joe;
Don’t do this!
Rectangle joe( );
When an object is created like this
Employee joe;
the employee object is stored on the stack. It is a local variable.
Passing Objects as Parameters
We always want to pass objects by reference.To keep from having side effects, pass byconstant reference. For example:
void printRectangle(const Rectangle&);
Lab #3 will give you some practicedesigning a class and writinga program in C++ to use it.