Download - Objects and Classes
-
5/27/2018 Objects and Classes
1/701
-
5/27/2018 Objects and Classes
2/70
Introduction
Previously, programmers starting a project would sit
down almost immediately and start writing code.
As programming projects became large and more
complicated, it was found that this approach did not
work very well. The problem was complexity. Large programs are probably the most complicated
entities ever created by humans.
Because of this complexity, programs are prone to error,
and software errors can be expensive and even life
threatening (in air traffic control, for example).
Three major innovations in programming have been
devised to cope with the problem of complexity. 2
-
5/27/2018 Objects and Classes
3/70
Object Oriented Programming
Object Oriented Programming offers a new and powerful
way to cope with complexity.
Instead of viewing a program as a series of steps to be
carried out, it views it as a group of objects that have
certain properties and can take certain actions. This may sound obscure until you learn more about it,
but it results in programs that are clearer, more reliable,
and more easily maintained.
A major goal of this course is to teach object-oriented
programming using C++ and cover all its major features.
3
-
5/27/2018 Objects and Classes
4/70
The Unified Modeling Language
The Unified Modeling Language (UML) is a graphical
language consisting of many kinds of diagrams.
It helps program analysts figure out what a program
should do, and helps programmers design and
understand how a program works. The UML is a powerful tool that can make programming
easier and more effective.
We introduce each UML feature where it will help to
clarify the OOP topic being discussed.
In this way you learn the UML painlessly at the same time
the UML helps you to learn C++.
4
-
5/27/2018 Objects and Classes
5/70
Class
A classserves as a plan, or template. It specifies what
data and what functions will be included in objectsof
that class.
Defining the classdoesnt create any objects, just as the
type intdoesnt create any variables. A classis thus a description of a number of similar
objects.
5
-
5/27/2018 Objects and Classes
6/70
#include
#includeusingnamespacestd;
classstudent // define a class (a concept){
private:intage; // class data (attributes)
public:voidset_age(intg) // member function (method){ // to set ageage = g;
}voidshow_age() // member function to display age{cout
-
5/27/2018 Objects and Classes
7/70
intmain()
{ student Ali, Usman; // define two objects of class studentAli.set_age(21); // call member function to set ageUsman.set_age(18);
Ali.show_age(); // call member function to display ageUsman.show_age();
system("PAUSE");return0;
}
7
A Simple Class (2/2)
-
5/27/2018 Objects and Classes
8/70
An objecthas the same relationship to a classthat a
variable has to a data type.
An objectis said to be an instanceof a class, in the same
way my Corolla is an instanceof a vehicle.
In the program the class, whose name is student, isdefined in the first part of the program.
In main(), we define two objectsAli and Usman that are
instancesof that class.
Each of the two objectsis given a value, and each displays
its value.
8
Classes and Objects
-
5/27/2018 Objects and Classes
9/70Syntax for class definition 9
Defining the Class
-
5/27/2018 Objects and Classes
10/70
Defining the Class
The definition starts with the keyword class, followed by
the class namestudentin this Example.
The body of the class is delimited by braces and
terminated by a semicolon.
An objecthas the same relationship to a classthat avariable has to a data type.
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.
The primary mechanism for hiding data is to put it in a
class and make itprivate. 10
-
5/27/2018 Objects and Classes
11/70
Defining the Class
Privatedata or functions can only be accessed from
within the class.
Publicdata or functions, on the other hand, are
accessible from outside the class.
The data member agefollows the keywordprivate, so itcan be accessed from within the class, but not from
outside.
Member functions (also called methodsor messages) are
functions that are included within a class.
There are two member functions in studentclass:
set_age() and show_age().
11
-
5/27/2018 Objects and Classes
12/70
Defining the Class
Because
set_age()and
show_age()
follow the keyword
public, they can
be accessed from
outside the class.
In a class the functions
do not occupy memory until an object of the class is
created.
12
-
5/27/2018 Objects and Classes
13/70
Defining the Class
Remember that the definition of the classstudent
does not create any objects. It only describes how they
will look when they are created.
Defining objects means creating them. This is also called
instantiatingthem, because an instanceof the classiscreated. An object is an instanceof a class.
ali.set_age(21);This syntax is used to call amember functionthat is associated with a specific object
ali.Member functions of a classcan be accessed only by an
objectof that class.
13
-
5/27/2018 Objects and Classes
14/70
// mobile.cpp demonstrates mobile phone as an object
#include#include
usingnamespacestd;classmobile // class name should be the name of a concept{
private:
string company_name;string model_number;
string emi_number;
floatcost;
public:
voidset_info(string cn,string mn, string emi, floatprice){ // set data
company_name = cn;
model_number = mn;
emi_number = emi;
cost = price;
} 14
Using Mobile Phone as an Object (1/2)
-
5/27/2018 Objects and Classes
15/70
voidshow_info()
{ // display datacout
-
5/27/2018 Objects and Classes
16/70
If you were designing an inventory program you might
actually want to create a class something like mobile.
Its an example of a C++ object representing a physical
object in the real worlda mobile phone.
Standard C++ includes a new class called string. Using stringobject, you no longer need to worry about
creating an array of the right size to hold string variables.
The string class assumes all the responsibility for memory
management.
Using Mobile Phone as an Object
16
-
5/27/2018 Objects and Classes
17/70
#include
#includeusingnamespacestd;
classHeight{ // A Height class
private:
intfeet;
floatinches;
public:voidset(intft, floatin){
feet = ft; inches = in;
}
voidget(){ // get height information from user
cout
-
5/27/2018 Objects and Classes
18/70
};
intmain()
{
Height H1, H2; // define two height objects
H1.set(4, 9.35F); // set feet = 4 and inches = 9.35 in H1 object
H2.get(); // get feet and inches info from user for H2
// display height information from H1 and H2 Objects
cout
-
5/27/2018 Objects and Classes
19/70
Constructors
We see that member functionscan be used to give values
to the data items in an object.
Sometimes, however, its convenient if an object can
initializeitself when its first created, without requiring a
separate call to a member function. Automatic initialization is carried out using a special
member function called a constructor.
A constructoris a member function that is executed
automatically whenever an object is created.
Constructor has the same name of class and it has no
return type.
19
-
5/27/2018 Objects and Classes
20/70
// A Constructor Example
#includeusingnamespacestd;
classHouse{
private:
doublearea; // area in square feet
public:
House() : area(1000){ // a zero (no) argument constructorcout area;
}
}; 20
Constructors: House Example (1/2)
-
5/27/2018 Objects and Classes
21/70
intmain()
{ House H1, H2; // define objects and calls constructor
cout
-
5/27/2018 Objects and Classes
22/70
#include // for cin and cout
#include // for rand(), srand() and system()#include // for time()
usingnamespacestd;
classDice{
private:
intnumber;
public:Dice():number(1){ // zero (no) argument constructor
// Sets the default number rolled by a dice to 1
// seed random number generator with current system time
srand(time(0));
}
introll() //Function to roll a dice.{ // This function uses a random number generator to randomly
// generate a number between 1 and 6, and stores the number
// in the instance variable number and returns the number.
number = rand() % 6 + 1;
returnnumber;
} 22
Constructors: A Dice Example (1/2)
-
5/27/2018 Objects and Classes
23/70
intget_number() // Function to return the number on the top face
{// of the die. It returns the value of the variable number.returnnumber;
}
};
intmain(){Dice d1,d2;
cout
-
5/27/2018 Objects and Classes
24/70
Destructors
You might guess that another function is called
automatically when an object is destroyed. This is indeedthe case. Such a function is called a destructor.
A destructoralso has the same name as the class name
but is preceded by a tilde (~) sign: Like constructors, destructors do not have a return value.
They also take no arguments.
The most common use of destructors is to de-allocate
memorythat was allocated for the object by the
constructor.
24
-
5/27/2018 Objects and Classes
25/70
#include
usingnamespacestd;
classHouse{
private: doublearea; // area in square feet
public:
House() : area(1000) // a zero argument const.
{ cout
-
5/27/2018 Objects and Classes
26/70
// A Constructor Example
#include
usingnamespacestd;
classHouse{
private: doublearea; // area in square feet
public:
House() : area(1000) // a zero (no) argument constructor
{ cout
-
5/27/2018 Objects and Classes
27/70
Objects as Function Arguments
Next program demonstrates some new aspects of
classes, which are:
Constructor Overloading
Defining Member Functions Outside The Class
Objects as Function Arguments.
27
-
5/27/2018 Objects and Classes
28/70
// englcon.cpp constructors, adds objects using member function
#include
#include
usingnamespacestd;
classDistance // English Distance class
{
private:
intfeet; floatinches;
public:
Distance() : feet(0), inches(0.0)
{ cout inches;
} 28
Objects as Function Arguments (1/3)
-
5/27/2018 Objects and Classes
29/70
voidshowdist(){ // display distance
cout
-
5/27/2018 Objects and Classes
30/70
intmain()
{
Distance dist1, dist3; // Calls no args. constructor
Distance dist2(11, 6.25); // Calls two args. constructor
dist1.getdist(); // get dist1 from user
dist3.add_dist(dist1, dist2); // dist3 = dist1 + dist2
// display all lengths
cout
-
5/27/2018 Objects and Classes
31/70
Constructors Overloading
Since there are now two explicit constructors with the
same name, Distance(), we say the constructor isoverloaded.
Which of the two constructors is executed when an
object is created depends on how many arguments areused in the definition:
Distance length;
// calls first constructor
Distance width(11, 6.0);
// calls second constructor
31
-
5/27/2018 Objects and Classes
32/70
Member Functions Defined Outside the Class
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.
32
-
5/27/2018 Objects and Classes
33/70
Objects as Arguments
Since add_dist()is a member functionof the Distanceclass,
it can access the privatedata in any object of classDistance supplied to it as an argument, using names like
dist1.inchesand dist2.feet.
In the following statement dist3.add_dist(dist1, dist2); add_dist() can access dist3, the object for which it was
called, it can also access dist1and dist2, because they are
supplied as arguments.
When the variables feetand inchesare referred to within
this function, they refer to dist3.feetand dist3.inches.
Notice that the result is not returned by the function. The
return typeof add_dist()is void. 33
-
5/27/2018 Objects and Classes
34/70
Objects as Arguments
The result is stored automatically in the dist3object.
To summarize, every callto a member functionis
associated with a particular object(unless its a static
function; well get to that later).
Using the member namesalone (feetand inches), thefunction has direct access to all the members, whether
privateor public, of that object.
member functionsalso have indirect access, using the
objectname and the membername, connected with the
dot operator (dist1.inchesor dist2.feet) to other objects of
the same classthat are passed as arguments.
34
-
5/27/2018 Objects and Classes
35/70
35
10
8
11
6.25
22
2.25
-
5/27/2018 Objects and Classes
36/70
The Default Copy Constructor
Weve seen two ways to initialize objects.
A no-argument constructor can initialize data members to
constant values
A multi-argument constructor can initialize data members to
values passed as arguments.
You can also initialize one object with another object of
the same type. Surprisingly, you dont need to create a
special constructor for this; one is already built into all
classes. Its called the default copy constructor. Its a one
argument constructor whose argument is an object of
the same class as the constructor. The next program
shows how this constructor is used. 36
-
5/27/2018 Objects and Classes
37/70
// ecopycon.cpp initialize objects using default copy constr.
#include
#include
usingnamespacestd;
classDistance
{ // English Distance class
private:
intfeet; floatinches;
public:
Distance() : feet(0), inches(0.0) // constructor (no args)
{ cout inches;
} 37
The Default Copy Constructor (1/2)
-
5/27/2018 Objects and Classes
38/70
voidshowdist(){ //display distance
cout
-
5/27/2018 Objects and Classes
39/70
// englret.cpp function returns value of type Distance
#include
#include
usingnamespacestd;
classDistance{ // English Distance class
private:
intfeet; floatinches;
public:Distance() : feet(0), inches(0.0) // constructor (no args)
{ cout inches;
}
39
Returning Objects from Functions (1/3)
Returning Objects from Functions
-
5/27/2018 Objects and Classes
40/70
voidshowdist() //display distance
{ cout
-
5/27/2018 Objects and Classes
41/70
intmain()
{
Distance dist1, dist3; // define two lengths
Distance dist2(11, 6.25); // define, initialize dist2
dist1.getdist(); // get dist1 from user
dist3 = dist1.add_dist(dist2); // dist3 = dist1 + dist2
cout
-
5/27/2018 Objects and Classes
42/70
Returning Objects from Functions
To execute the statement dist3 = dist1.add_dist(dist2);
A temporary object of class Distanceis created to store
the sum.
The sum is calculated by adding two distances.
The first is the object dist1, of which add_dist()is a member. Itsmember data is accessed in the function as feetand
inches.
The second is the object passed as an argument, dist2.
Its member data is accessed as d2.feetand d2.inches.
The result is stored in tempand accessed as temp.feetand
temp.inches.
42
-
5/27/2018 Objects and Classes
43/70
Returning Objects from Functions
The tempobject is then returned by the function using
the statement returntemp;
The statement in main() assigns it to dist3.
Notice that dist1is not modified; it simply supplies data
to add_dist(). Figure on next slide shows how this looks.
In the topic, Operator Overloading, well see how to
use the arithmetic + operator to achieve the even more
natural expression like dist3 = dist1 + dist2;
43
-
5/27/2018 Objects and Classes
44/70
44
10
8
11
6.25
22
2.25
-
5/27/2018 Objects and Classes
45/70
Structures and Classes
In fact, you can use structures in almost exactly the same
way that you use classes. The only formal differencebetween classand structis that in a class the members
are private by default, while in a structure they are public
by default. You can just as well write
classfoo
{
intdata1;public:
voidfunc();
}; //and the data1 will still be private.
45
-
5/27/2018 Objects and Classes
46/70
Structures and Classes
If you want to use a structure to accomplish the same
thing as this class, you can dispense with the keywordpublic, provided you put the public members before the
private ones
structfoo{voidfunc();
private:
intdata1;
}; // since public is the default.
However, in most situations programmers dont use a
structthis way. They use structures to group only data,
and classes to group both data and functions.46
-
5/27/2018 Objects and Classes
47/70
Classes, Objects and Memory
you might have the impression that each objectcreated
from a class contains separatecopiesof that classs dataand member functions.
Its true that each objecthas its own separate data items
But all the objectsin a given classuse the same memberfunctions.
The member functions are createdandplacedin memory
onlyoncewhen they are definedin the classdefinition.
Since the functions for each object are identical. The data
items, however, will hold different values.
47
-
5/27/2018 Objects and Classes
48/70
48
-
5/27/2018 Objects and Classes
49/70
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 manyobjectsthere are.
A staticdata item is useful when all objects of the same
class must sharea common item of information.
A member variable definedas statichas characteristics
similar to a normal static variable: It is visibleonly within
the class, but its lifetimeis the entireprogram. It conti-
nues to exist even if there are no objectsof the class. 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.49
-
5/27/2018 Objects and Classes
50/70
Static Class Data
Why would you want to use staticmember data? As an
example, suppose an object needed to know how manyother objects of its class were in the program.
In a road-racing game, for example, a race car might want
to know how many other cars are still in the race.
In this case a staticvariable Total_Carscould be included
as a member of the class. All the objects would have
access to this variable. It would be the same variable for
all of them; they would all see the same number ofTotal_Cars.
50
Static Data Class
-
5/27/2018 Objects and Classes
51/70
Static Data Class
(1/2)// statdata.cpp demonstrates a simple static data member
#include
usingnamespacestd;
classCar
{
private:
staticintTotal_Cars; // only one data item for all objects
// note: "declaration" only!
public:
Car() // increments count when object created
{ Total_Cars++; }
intHow_Many() // returns count
{ returnTotal_Cars; }
~Car()
{ Total_Cars--; }
};
intCar::Total_Cars = 0; // *definition* of count 51
Static Data Class
-
5/27/2018 Objects and Classes
52/70
intmain()
{
Car Toyota, Honda, Suzuki; // create three objects
cout
-
5/27/2018 Objects and Classes
53/70
Static Class Data
Ordinary variablesare usually declared (the compiler is
told about their name and type) and defined (thecompiler sets aside memory to hold the variable) in the
same statement. e.g. int a;
Static member data, on the other hand, requires two
separate statements.
The variables declarationappears in the classdefinition,
but the variable is actually definedoutsidethe class, in much
the same way as a global variable. If staticmember data were defined inside the class, it
would violate the idea that a class definition is only a
blueprint and does not set aside any memory.53
t M b F ti
-
5/27/2018 Objects and Classes
54/70
//constfu.cpp demonstrates const member functions
classaClass
{
private:
intalpha;public:
voidnonFunc() // non-const member function
{
alpha = 99; // OK
}
voidconFunc() const // const member function
{
alpha = 99; // ERROR: cant modify a member
}
};
constMember Function
A constmember function guarantees that it will never
modify any of its classs member data.
54
Distance Class and Use of const
-
5/27/2018 Objects and Classes
55/70
// const member functions & const arguments to member functions
#include
usingnamespacestd;
classDistance // English Distance class
{
private:
intfeet;
floatinches;
public: // constructor (no args)
Distance() : feet(0), inches(0.0)
{ } // constructor (two args)
Distance(intft, floatin) : feet(ft), inches(in){ }
voidgetdist(){ // get length from user
cout > feet;
cout > inches;
} 55
Distance Class and Use of const
(1/3)
Distance Class and Use of const
-
5/27/2018 Objects and Classes
56/70
voidshowdist() const // display distance
{ cout
-
5/27/2018 Objects and Classes
57/70
intmain()
{
Distance dist1, dist3; // define two lengthsDistance dist2(11, 6.25); // define, initialize dist2
dist1.getdist(); // get dist1 from user
dist3 = dist1.add_dist(dist2); // dist3 = dist1 + dist2
//display all lengths
cout
-
5/27/2018 Objects and Classes
58/70
constMember Function Arguments
if an argument is passed to an ordinary function by
reference, and you dont want the function to modify it,the argument should be made const in the function
declaration (and definition). This is true of member
functions as well.Distance Distance::add_dist(constDistance& d2) const{
In above line, argument to add_dist() is passed by
reference, and we want to make sure that wont modify
this variable, which is dist2 in main().
Therefore we make the argument d2 to add_dist() const
in both declaration and definition.
58
t Obj t
-
5/27/2018 Objects and Classes
59/70
constObjects
In several example programs, weve seen that we can
apply constto variables of basic types such as intto keepthem from being modified.
In a similar way, we can apply constto objectsof classes.
When an objectis declared as const, you cant modify it.
It follows that you can use only const member functions
with it, because theyre the only ones that guarantee not
to modify it. e.g. A football field (for American-style
football) is exactly 300 feet long. If we were to use thelength of a football field in a program, it would make
sense to make it const, because changing it would
represent the end of the world for football fans.59
constObjects
-
5/27/2018 Objects and Classes
60/70
// constObj.cpp constant Distance objects
#include
usingnamespacestd;classDistance // English Distance class
{
private:
intfeet;
floatinches;
public:
// 2-arg constructor
Distance(intft, floatin) : feet(ft), inches(in)
{ }
voidgetdist() // user input; non-const function{
cout > feet;
cout > inches;
}
60
j
(1/2)
constObjects
-
5/27/2018 Objects and Classes
61/70
voidshowdist() const // display distance; const function
{
cout
-
5/27/2018 Objects and Classes
62/70
Implement a Circleclass. Each object of this class will
represent a circle, storing its radiusand the x and ycoordinates of its center as floats.
One constructorshould initialize it data to 0, and another
constructor should initialize it to fixed values given by user.
Make void setValues(float, float, float) functions to set x,y
and radius.
Make float area()function, and a float circumference()
function to returnareaand circumference.
Make void print() function to display xycoordinates and
radiusof a circle.
Call these functions in main() to display their working.
g
No.1
62
Assignment Question
-
5/27/2018 Objects and Classes
63/70
Create a class Rectanglewith attributes lengthand width,
each of which defaults to 1.Provide member functions that calculate the perimeterand
the areaof the rectangle.
Also, provide setand getfunctions for the lengthand width
attributes.
The setfunctions should verify that lengthand widthare
each floating-pointnumbers larger than 0.0 and less than
20.0.
Make a Drawfunction that makes a rectangle using a
character *on console.
g
No.2
63
Assignment Question
-
5/27/2018 Objects and Classes
64/70
Create a class called time
that has separate intmember data for hours, minutes, andseconds.
One constructorshould initialize this data to 0, and another
constructor should initialize it to fixed values.
Make void print()to display time in 23:59:59 format.
Make void setHour( int ) to set hours.
Make void setminute (int ) to set minutes.
Make void setSecond( int ) to set seconds.
Make void setTime( int, int, int ) to set hour, minute, second
Make int getHour(); int getMinute(); int getSecond();
to return hours, minuteand secondsrespectively.
g
No.3
64
Assignment Question
-
5/27/2018 Objects and Classes
65/70
include a tickmember function that increments the
time stored in a Time object by one second. An addmember function should add two objects of
type time passed as arguments.
Be sure to test the following cases:1. Incrementing into the next minute.
2. Incrementing into the next hour.
3. Incrementing into the next day (i.e., 23:59:59 to 00:00:00).
Make 1000 times loop in a main function. Call tick and
printTimefunctions in that loop for an object. Also make twoobjects and add them to a third object and print their values.
g
No.3
65
Assignment Question
-
5/27/2018 Objects and Classes
66/70
Create a class called Rationalfor performing arithmetic
with fractions. Write a program to test your class. Use integer variables to represent the privatedata of
the class the numeratorand the denominator.
Provide a constructorthat enables an object of this classto be initialized when it is declared. The constructor
should contain default values in case no initializers are
provided and should store the fraction in reduced form.
For example, the fraction 2/4would be stored in theobject as 1in the numeratorand 2in the denominator.
Provide publicmember functions that perform each of
the following tasks:
g
No.4
66
Assignment Question
-
5/27/2018 Objects and Classes
67/70
1. Adding two Rational numbers.
The result should be stored in reduced form.
1. Subtracting two Rational numbers.
The result should be stored in reduced form.
3. Multiplying two Rational numbers.
The result should be stored in reduced form.
3. Dividing two Rational numbers.
The result should be stored in reduced form.3. Printing Rational numbers in the form a/b, where a is
the numerator and b is the denominator.
4. Printing Rational numbers in floating-point format.
g
No.4
67
Assignment Question
-
5/27/2018 Objects and Classes
68/70
The equation of a line in standard form is ax + by = c, where
both aand bcannot be zero, and a, b, and care real numbers. If bis not equal to zero, then a/b is the slopeof the line.
If ais equal to zero, then it is a horizontalline
if b is equal to zero, then it is a verticalline.
The slope of a vertical line is undefined.
Two lines are parallelif they have the sameslopeor both
are vertical lines.
Two lines are perpendicularif either one of the lines is
horizontal and the other is vertical or the productof theirslopesis 1
Design the class lineTypeto store a line. To store a line, you
need to store the values of a (coefficient of x), b(coefficient of
y), and c.
No.5
68
Assignment Question
-
5/27/2018 Objects and Classes
69/70
Your class must contain the following operations.
If a line is nonvertical, then determine its slope. Determine if two lines are equal. Two lines a1x + b1y = c1
and a2x +b2y = c2 are equal if
either a1 = a2, b1 = b2, and c1= c2
or a1 = ka2, b1= kb2, and c1 = kc2 for some real numberk.)
Determine if two lines are parallel.
Determine if two lines are perpendicular.
If two lines are not parallel, then find the point of
intersection.
Add appropriate constructorsto initialize variables of
lineType.
Also write a ro ram to test our class.
No.5
69
Assignment Question
-
5/27/2018 Objects and Classes
70/70
Create a class TicTacToeto play the game of tic-tac-toe
The class contains as private data a 3-by-3 two-dimensional arrayof integers.
The constructorshould initialize the empty board to all
zeros.Allow two human players.
place a 1in the specified square, wherever the first player moves, .
Place a 2wherever the second player moves.
Each move must be to an empty square.
After each move, determine whether the game has been
wonor is a draw.
No.6