ch06 objects and classes
TRANSCRIPT
-
8/6/2019 Ch06 Objects and Classes
1/22
1
-
8/6/2019 Ch06 Objects and Classes
2/22
INTRODUCTION
Previously, programmers starting a project would sitPreviously, programmers starting a project would sitdown almost immediately and start writing code.down almost immediately and start writing code.
As programming projects became large and moreAs programming projects became large and more
complicated, it was found that this approach did notcomplicated, it was found that this approach did not
work very well. The problem was complexity.work very well. The problem was complexity.
Large programs are probably the most complicatedLarge programs are probably the most complicated
entities ever created by humans.entities ever created by humans.
Because of this complexity, programs are prone to error,Because of this complexity, programs are prone to error,
and software errors can be expensive and even lifeand software errors can be expensive and even life
threatening (in air traffic control, for example).threatening (in air traffic control, for example).
Three major innovations in programming have beenThree major innovations in programming have been
devised to cope with the problem of complexity. They aredevised to cope with the problem of complexity. They are2
-
8/6/2019 Ch06 Objects and Classes
3/22
INTRODUCTION
Object
Object--oriented programming (
OOP)oriented programming (
OOP)
The Unified Modeling Language (UML)The Unified Modeling Language (UML)
Improved software development processesImproved software development processes
You will be taught the C++ language with these developYou will be taught the C++ language with these develop--
mentsments in mind.in mind. You will not only learn a computer language, but newYou will not only learn a computer language, but new
ways of conceptualizing software development.ways of conceptualizing software development.
Other famousObject Oriented languages are JAVA, C# (COther famousObject Oriented languages are JAVA, C# (C
CharpCharp), VB.NET (Visual Basic Dot Net).), VB.NET (Visual Basic Dot Net).
3
-
8/6/2019 Ch06 Objects and Classes
4/22
OBJECT ORIENTED PROGRAMMING
Object Oriented Programming offers a new and powerfulObject Oriented Programming offers a new and powerfulway to cope with complexity.way to cope with complexity.
Instead of viewing a program as a series of steps to beInstead of viewing a program as a series of steps to be
carried out, it views it as a group of objects that havecarried out, it views it as a group of objects that have
certain properties and can take certain actions.certain properties and can take certain actions.
This may sound obscure until you learn more about it,This may sound obscure until you learn more about it,
but it results in programs that are clearer, more reliable,but it results in programs that are clearer, more reliable,
and more easily maintained.and more easily maintained.
A major goal of this course is to teach objectA major goal of this course is to teach object--orientedoriented
programming using C++ and cover all its major features.programming using C++ and cover all its major features.
4
-
8/6/2019 Ch06 Objects and Classes
5/22
THE UNIFIED MODELING LANGUAGE
The Unified Modeling Language (UML) is a graphicalThe Unified Modeling Language (UML) is a graphicallanguage consisting of many kinds of diagrams.language consisting of many kinds of diagrams.
It helps program analysts figure out what a programIt helps program analysts figure out what a program
should do, and helps programmers design andshould do, and helps programmers design and
understand how a program works.understand how a program works.
The UML is a powerful tool that can make programmingThe UML is a powerful tool that can make programming
easier and more effective.easier and more effective.
We introduce each UML feature where it will help toWe introduce each UML feature where it will help to
clarify the OOP topic being discussed.clarify the OOP topic being discussed.
In this way you learn the UML painlessly at the same timeIn this way you learn the UML painlessly at the same time
the UML helps you to learn C++.the UML helps you to learn C++.
5
-
8/6/2019 Ch06 Objects and Classes
6/22
CLASS
AA classclass serves as a plan, or template. It specifies whatserves as a plan, or template. It specifies whatdata and what functions will be included indata and what functions will be included in objectsobjects ofof
thatthat classclass..
Defining theDefining the classclass doesnt create anydoesnt create any objectsobjects, just as the, just as the
typetype intintdoesnt create any variables.doesnt create any variables.
AA classclass is thus a description of a number of similaris thus a description of a number of similar
objects.objects.
PrincePrince,, StingSting, and, and MadonnaMadonna areare membersmembers of the class ofof the class of
rock musiciansrock musicians..
There is no one person called There is no one person called rock musicianrock musician but specific but specific
people with specific names are members of this class ifpeople with specific names are members of this class if
they possess certainthey possess certain characteristicscharacteristics.. 6
-
8/6/2019 Ch06 Objects and Classes
7/22
CLASS
Picture a programming objectPicture a programming objectjust like any normal object injust like any normal object in
the real world.the real world.
Each real world object has itsEach real world object has its
own properties and specificown properties and specificthings that you can do with it.things that you can do with it.
For example, a bow has specificFor example, a bow has specific
properties such as color,properties such as color,
number of arrows, and weightnumber of arrows, and weight
and specific capabilities such asand specific capabilities such as
the ability to fire .the ability to fire .
7
-
8/6/2019 Ch06 Objects and Classes
8/22
CLASS
two Bow objects are declared using the Bow class, thetwo Bow objects are declared using the Bow class, the
Bow class describes the properties of a bow, each of theBow class describes the properties of a bow, each of the
two Bow objects has distinct values for these propertiestwo Bow objects has distinct values for these properties 8
-
8/6/2019 Ch06 Objects and Classes
9/22
A SIMPLE CLASS
// smallobj.cpp demonstrates a small, simple object#include
using namespace std;
class smallobj // define a class (a concept)
{
private:
int somedata; // class data (attributes)
public:
voidsetdata(int d){ // member function (method)to
somedata = d; // set data
}
voidshowdata(){ // member function to display data
cout
-
8/6/2019 Ch06 Objects and Classes
10/22
A SIMPLE CLASS
intmain(){
smallobj s1, s2; // define two objects of class smallobj
s1.setdata(1066); // call member function to set data
s2.setdata(1776);
s1.showdata(); // call member function to display data
s2.showdata();
system("PAUSE");
return 0;
}
10
-
8/6/2019 Ch06 Objects and Classes
11/22
CLASSES AND OBJECTS
AnAn objectobjecthas the same relationship to ahas the same relationship to a classclass that athat avariable has to a data type.variable has to a data type.
AnAn objectobjectis said to be anis said to be an instanceinstance of a class, in the sameof a class, in the same
way my 1954 Chevrolet is anway my 1954 Chevrolet is an instanceinstance of a vehicle.of a vehicle.
In the program theIn the program the classclass , whose name is, whose name is smallobjsmallobj, is, is
defined in the first part of the program.defined in the first part of the program.
In main(), we define twoIn main(), we define two objectsobjects s1 and s2 that ares1 and s2 that are
instancesinstances of that class.of that class.
Each of the twoEach of the two objectsobjects is given a value, and each displaysis given a value, and each displays
its value.its value.
11
-
8/6/2019 Ch06 Objects and Classes
12/22
DEFINING THE CLASS
Syntax for class definitionSyntax for class definition12
-
8/6/2019 Ch06 Objects and Classes
13/22
DEFINING THE CLASS
The definition starts with the keyword class, followed byThe definition starts with the keyword class, followed bythe class namethe class namesmallobjsmallobj in this Example.in this Example.
The body of the class is delimited by braces andThe body of the class is delimited by braces and
terminated by a semicolon.terminated by a semicolon.
AnAn objectobjecthas the same relationship to ahas the same relationship to a classclass that athat avariable has to a data type.variable has to a data type.
A key feature of objectA key feature of object--oriented programming is dataoriented programming is data
hiding. it means that data is concealed within a class sohiding. it means that data is concealed within a class so
that it cannot be accessed mistakenly by functionsthat it cannot be accessed mistakenly by functions
outside the class.outside the class.
The primary mechanism for hiding data is to put it in aThe primary mechanism for hiding data is to put it in a
class and make itclass and make it privateprivate.. 13
-
8/6/2019 Ch06 Objects and Classes
14/22
DEFINING THE CLASS
PrivatePrivate data or functions can only be accessed fromdata or functions can only be accessed fromwithin the class.within the class.
PublicPublic data or functions, on the other hand, aredata or functions, on the other hand, are
accessible from outside the class.accessible from outside the class.
The data memberThe data member somedatasomedata follows the keywordfollows the keywordprivateprivate,,so it can be accessed from within theso it can be accessed from within the classclass, but not from, but not from
outside.outside.
Member functionsMember functions (also called(also called methodsmethods oror messagesmessages) are) are
functions that are included within a class.functions that are included within a class.
There are two member functions inThere are two member functions in smallobjsmallobj:: setdatasetdata()()
andand showdatashowdata().().
14
-
8/6/2019 Ch06 Objects and Classes
15/22
DEFINING THE CLASS
BecauseBecause setdatasetdata()()andand showdatashowdata()()
follow the keywordfollow the keyword
publicpublic, they can be, they can be
accessed fromaccessed fromoutside the class.outside the class.
In a class theIn a class the
functions do notfunctions do not
occupy memoryoccupy memoryuntil an object ofuntil an object of
the class is created.the class is created.
15
-
8/6/2019 Ch06 Objects and Classes
16/22
DEFINING THE CLASS
Remember that the definition of theRemember that the definition of the classclass smallobjsmallobj doesdoesnot create anynot create any objectsobjects. It only describes how they will. It only describes how they will
look when they are created.look when they are created.
Defining objectsDefining objects means creating them. This is also calledmeans creating them. This is also called
instantiatinginstantiating them, because anthem, because an instanceinstance of theof the classclass isiscreated. An object is ancreated. An object is an instanceinstance of a class.of a class.
s1.setdata(1066);s1.setdata(1066); This syntax is used to call aThis syntax is used to call a membermember
functionfunction that is associated with a specific object s1.that is associated with a specific object s1.
Member functionsMember functions of aof a classclass can be accessed only by ancan be accessed only by an
objectobjectof thatof that classclass..
16
-
8/6/2019 Ch06 Objects and Classes
17/22
WIDGET PARTS AS OBJECTS
(1/2)
// objpart.cpp widget part as an object#include
using namespace std;
classpart{ // define class
private:
intmodelnumber; // ID number of widget
intpartnumber; // ID number of widget part
float cost; // cost of part
public:
voidsetpart(intmn, intpn, float c){ // set data
modelnumber = mn;
partnumber = pn;
cost = c;
}
voidshowpart(){ // display data
cout
-
8/6/2019 Ch06 Objects and Classes
18/22
WIDGET PARTS AS OBJECTS
(1/2)
cout
-
8/6/2019 Ch06 Objects and Classes
19/22
CIRCLES AS OBJECTS
// circles.cpp circles as graphics objects#include "msoftcon.h" // for graphics functions
class circle{ // graphics circle
protected:
int xCo, yCo; // coordinates of center
int radius;
color fillcolor; // color
fstyle fillstyle; // fill pattern
public: // sets circle attributes
voidset(int x, int y, int r, color fc, fstyle fs){
xCo = x; yCo = y; radius = r;
fillcolor = fc; fillstyle = fs;
}
voiddraw(){ // draws the circle
set_color(fillcolor); // set color
set_fill_style(fillstyle); // set fill
19
-
8/6/2019 Ch06 Objects and Classes
20/22
CIRCLES AS OBJECTS
draw_circle(xCo, yCo, radius);// draw solid circle}
};
intmain(){
init_graphics(); // initialize graphics system
circle c1, c2, c3; // create circles
//set circle attributes
c1.set(15, 7, 5, cBLUE, X_FILL);
c2.set(41, 12, 7, cRED, O_FILL);
c3.set(65, 18, 4, cGREEN, MEDIUM_FILL);
c1.draw(); //draw circles
c2.draw();
c3.draw();
set_cursor_pos(1, 25); // lower left corner
system("PAUSE");
return 0;
} 20
-
8/6/2019 Ch06 Objects and Classes
21/22
USING CLASS TO REPRESENT
DISTANCES
// englobj.cpp objects using English measurements#include
using namespace std;
class Distance{ // English Distance class
private:
int feet;
float inches;
public:
voidsetdist(int ft, float in) // set Distance to args
{ feet = ft; inches = in; }
voidgetdist(){ // get length from user
cout > feet;
cout > inches;
}
voidshowdist() // display distance
{ cout
-
8/6/2019 Ch06 Objects and Classes
22/22
USING CLASS TO REPRESENT
DISTANCES
intmain(){
Distance dist1, dist2; // define two lengths
dist1.setdist(11, 6.25); // set dist1
dist2.getdist(); // get dist2 from user
// display lengths
cout