Ch06 Objects and Classes (1)
-
Upload
waqar-ahmed -
Category
Documents
-
view
218 -
download
0
Transcript of Ch06 Objects and Classes (1)
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 1/70
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 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. They are2
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 3/70
Introduction
Object-oriented programming (OOP)
The Unified Modeling Language (UML)
Improved software development processes
You will be taught the C++ language with these develop-
ments in mind. You will not only learn a computer language, but new
ways of conceptualizing software development.
Other famous Object Oriented languages are JAVA, C# (C
Charp), VB.NET (Visual Basic Dot Net), Paython3, PHP5.
3
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 4/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.
4
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 5/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++.
5
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 6/70
Class
A class serves as a plan, or template. It specifies what
data and what functions will be included in objects of
that class.
Defining the class doesn’t create any objects, just as the
type int doesn’t create any variables. A class is thus a description of a number of similar
objects.
Prince, Sting, and Madonna are members of the class of
rock musicians.
There is no one person called “rock musician” but specific
people with specific names are members of this class if
they possess certain characteristics. 6
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 7/70
Class
Picture a programming object
just like any normal object in
the real world.
Each real world object has its
own properties and specificthings that you can do with it.
For example, a bow has specific
properties such as color,
number of arrows, and weightand specific capabilities such as
the ability to fire .
7
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 8/70
Class
two Bow objects are declared using the Bow class, the
Bow class describes the properties of a bow, each of the
two Bow objects has distinct values for these properties 8
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 9/70
A Simple Class
// smallobj.cpp demonstrates a small, simple object
#include <iostream> using namespace std;
class smallobj // define a class (a concept)
{
private:
int somedata; // class data (attributes)
public:
void setdata(int d){ // member function (method)to
somedata = d; // set data
}
void showdata(){ // member function to display data
cout << "Data is " << somedata << endl;
}
};
9
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 10/70
A Simple Class
int main()
{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
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 11/70
Classes and Objects
An object has the same relationship to a class that a
variable has to a data type.
An object is said to be an instance of a class, in the same
way my 1954 Chevrolet is an instance of a vehicle.
In the program the class , whose name is smallobj, isdefined in the first part of the program.
In main(), we define two objects s1 and s2 that are
instances of that class.
Each of the two objects is given a value, and each displays
its value.
11
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 12/70
Defining the Class
Syntax for class definition 12
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 13/70
Defining the Class
The definition starts with the keyword class, followed by
the class name—smallobj in this Example.
The body of the class is delimited by braces and
terminated by a semicolon.
An object has the same relationship to a class that 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 it private. 13
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 14/70
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 15/70
Defining the Class
Because setdata()
and showdata()
follow the keyword
public, they can be
accessed from
outside the class.
In a class the
functions do not
occupy memoryuntil an object of
the class is created.
15
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 16/70
Defining the Class
Remember that the definition of the class smallobj 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
instantiating them, because an instance of the class iscreated. An object is an instance of a class.
s1.setdata(1066); This syntax is used to call a member
function that is associated with a specific object s1.
Member functions of a class can be accessed only by an
object of that class.
16
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 17/70
Widget Parts as Objects (1/2)
// objpart.cpp widget part as an object
#include <iostream> using namespace std;
class part{ // define class
private:
int modelnumber; // ID number of widget
int partnumber; // ID number of widget part
float cost; // cost of part
public:
void setpart(int mn, int pn, float c){ // set data
modelnumber = mn;
partnumber = pn;
cost = c;
}
void showpart(){ // display data
cout << "Model " << modelnumber;
17
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 18/70
Widget Parts as Objects (1/2)
cout << ", part " << partnumber;
cout << ", costs $" << cost << endl;}
};
int main(){
part part1; // define object of class part
part1.setpart(6244, 373, 217.55F); // call member function
part1.showpart(); // call member function
system("PAUSE"); return 0;
}
If you were designing an inventory program you might
actually want to create a class something like part.
It’s an example of a C++ object representing a physical
object in the real world—a widget part. 18
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 19/70
Circles as Objects
// circles.cpp circles as graphics objects
#include "msoftcon.h" // for graphics functionsclass circle{ // graphics circle
protected :
int xCo, yCo; // coordinates of center
int radius;
color fillcolor; // colorfstyle fillstyle; // fill pattern
public: // sets circle attributes
void set(int x, int y, int r, color fc, fstyle fs){
xCo = x; yCo = y; radius = r;
fillcolor = fc; fillstyle = fs;
}
void draw(){ // draws the circle
set_color(fillcolor); // set color
set_fill_style(fillstyle); // set fill
19
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 20/70
Circles as Objects
draw_circle(xCo, yCo, radius);// draw solid circle
}};
int main(){
init_graphics(); // initialize graphics system
circle c1, c2, c3; // create circles
//set circle attributesc1.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
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 21/70
Using Class to Represent Distances
// englobj.cpp objects using English measurements
#include <iostream> using namespace std;
class Distance{ // English Distance class
private:
int feet;
float inches; public:
void setdist(int ft, float in) // set Distance to args
{ feet = ft; inches = in; }
void getdist(){ // get length from user
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void showdist() // display distance
{ cout << feet << "\’-" << inches << '\”'; }
}; 21
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 22/70
Using Class to Represent Distances
int main()
{Distance dist1, dist2; // define two lengths
dist1.setdist(11, 6.25); // set dist1
dist2.getdist(); // get dist2 from user
// display lengthscout << "\ndist1 = ";
dist1.showdist();
cout << "\ndist2 = ";
dist2.showdist();
cout << endl;
system("PAUSE");
return 0;
} 22
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 23/70
Constructors
We see that member functions can be used to give values
to the data items in an object .
Sometimes, however, it’s convenient if an object can
initialize itself when it’s 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 constructor is 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.
23
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 24/70
Constructors: Count Example (1/2)
// counter.cpp object represents a counter variable
#include <iostream> using namespace std;
class Counter{
private:
unsigned int count; // count
public:Counter() : count(0) // constructor
{ cout << "constructor has been called \n"; }
void inc_count() // increment count
{ count++; }
int get_count() // return count
{ return count; }
};
24
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 25/70
Constructors: Count Example (2/2)
int main()
{Counter c1, c2; // define and initialize
cout << "\nc1=" << c1.get_count(); // display
cout << "\nc2=" << c2.get_count();
c1.inc_count(); // increment c1
c2.inc_count(); // increment c2c2.inc_count(); // increment c2
cout << "\nc1=" << c1.get_count(); // display again
cout << "\nc2=" << c2.get_count();
cout << endl;
system("PAUSE");
return 0;
}
25
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 26/70
Circles using Constructor (1/2)
// circles.cpp circles as graphics objects
#include "msoftcon.h" // for graphics functionsclass circle{ // graphics circle
protected :
int xCo, yCo; // coordinates of center
int radius;
color fillcolor; // colorfstyle fillstyle; // fill pattern
public: // sets circle attributes
circle(int x, int y, int r, color fc, fstyle fs):
xCo(x), yCo(y), radius(r), fillcolor(fc), fillstyle(fs)
{ } // 3 argument constructor
void draw(){ // draws the circle
set_color(fillcolor); // set color
set_fill_style(fillstyle); // set fill
26
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 27/70
Circles using Constructor (2/2)
draw_circle(xCo, yCo, radius); //draw solid circle
}};
int main(){
init_graphics(); // initialize graphics system
//create circles
circle c1(15, 7, 5, cBLUE, X_FILL);circle c2(41, 12, 7, cRED, O_FILL);
circle c3(65, 18, 4, cGREEN, MEDIUM_FILL);
c1.draw(); // draw circles
c2.draw();
c3.draw();
set_cursor_pos(1, 25); // lower left corner
return 0;
}
27
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 28/70
Destructor
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 destructor also 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
memory that was allocated for the object by the
constructor.
28
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 29/70
Using Destructor
// foo.cpp demonstrates destructor
#include <iostream> using namespace std;
class Foo{
private:
int data;
public:Foo() : data(0) // constructor (same name as class)
{cout<< "Wakeup \n" ; }
~Foo() // destructor (same name with tilde)
{cout<< "ByeBye \n" ; }
};
int main(){
Foo s1, s2; // define two objects of class Foo
system( "PAUSE" ); // Foo *s3; s3 = new Foo; delete s3;
return 0;
} 29
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 30/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.
30
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 31/70
Objects as Function Arguments (1/3)
// englcon.cpp constructors, adds objects using member function
#include <iostream> using namespace std;
class Distance // English Distance class
{
private:
int feet;float inches;
public: // constructor (no args)
Distance() : feet(0), inches(0.0)
{ cout<< "No Arguments Constructor has been Called \n" ; }
//constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ cout<< "Two Arguments Constructor has been Called \n" ; }
31
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 32/70
Objects as Function Arguments (2/3)
void getdist(){ // get length from user
cout << "\nEnter feet: "; cin >> feet;cout << "Enter inches: "; cin >> inches;
}
void showdist(){ // display distance
cout << feet << "\'-" << inches << '\"';
}void add_dist( Distance, Distance ); // declaration
};
// member function is defined outside the class
void Distance::add_dist(Distance d2, Distance d3){
inches = d2.inches + d3.inches; // add the inches
feet = 0; // (for possible carry)
if(inches >= 12.0){ // if total exceeds 12.0,
inches -= 12.0; // then decrease inches by 12.0
feet++; // and increase feet by 1
} 32
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 33/70
Objects as Function Arguments (3/3)
feet += d2.feet + d3.feet; // add the feet
}int main(){
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 << "\ndist1 = "; dist1.showdist();
cout << "\ndist2 = "; dist2.showdist();
cout << "\ndist3 = "; dist3.showdist();
cout << endl;
return 0;
}
33
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 34/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
34
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 35/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.
35
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 36/70
Objects as Arguments
Since add_dist() is a member function of the Distance
class, it can access the private data in any object of classDistance supplied to it as an argument, using names like
dist1.inches and 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 dist1 and dist2, because they are
supplied as arguments.
When the variables feet and inches are referred to within
this function, they refer to dist3.feet and dist3.inches.
Notice that the result is not returned by the function. The
return type of add_dist() is void. 36
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 37/70
Objects as Arguments
The result is stored automatically in the dist3 object.
To summarize, every call to a member function is
associated with a particular object (unless it’s a static
function; we’ll get to that later).
Using the member names alone (feet and inches), thefunction has direct access to all the members, whether
private or public, of that object .
member functions also have indirect access, using the
object name and the member name, connected with thedot operator (dist1.inches or dist2.feet) to other object s
of the same class that are passed as arguments.
37
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 38/70
38
10
8
11
6.25
22
2.25
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 39/70
The Default Copy Constructor
We’ve seen two ways to initialize objects.
A no-argument constructor can initialize data members toconstant 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 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. The next program
shows how this constructor is used. 39
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 40/70
The Default Copy Constructor (1/2)
// ecopycon.cpp initialize objects using default copy constr.
#include <iostream> using namespace std;
class Distance{ // English Distance class
private:
int feet; float inches;
public:
Distance() : feet(0), inches(0.0) // constructor (no args)
{ cout<< "No Arguments Constructor has been Called \n" ; }
Distance(int ft, float in) : feet(ft), inches(in)
{ cout<< "Two Arguments Constructor has been Called \n" ; }void getdist(){ // get length from user
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
40
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 41/70
The Default Copy Constructor (2/2)
void showdist(){ //display distance
cout << feet << "\'-" << inches << '\"';}
};
int main(){
Distance dist1; // calls no arguments constructor
Distance dist2(11, 6.25); // calls two-arg constructorDistance dist3(dist2); // calls default copy constructor
Distance dist4 = dist2; // also calls default copy const.
// display all lengths
cout << "\ndist1 = "; dist1.showdist();
cout << "\ndist2 = "; dist2.showdist();cout << "\ndist3 = "; dist3.showdist();
cout << "\ndist4 = "; dist4.showdist();
cout << endl; return 0;
}
41
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 42/70
Returning Objects from Functions (1/3)
// englret.cpp function returns value of type Distance
#include <iostream> using namespace std;
class Distance{ // English Distance class
private:
int feet; float inches;
public:Distance() : feet(0), inches(0.0) // constructor (no args)
{ cout<< "No Arguments Constructor has been Called \n" ; }
// constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ cout<< "Two Arguments Constructor has been Called \n" ; }
void getdist(){ // get length from user
cout << "Enter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
} 42
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 43/70
Returning Objects from Functions (2/3)
void showdist(){ //display distance
cout << feet << "\'-" << inches << '\"';}
Distance add_dist(Distance); // add
};
// add this distance to d2, return the sum Distance Distance::add_dist(Distance d2){
Distance temp; // temporary variable
temp.inches = inches + d2.inches; // add the inches
if(temp.inches >= 12.0){ // if total exceeds 12.0,
temp.inches -= 12.0; // then decrease inches by 12.0 and temp.feet = 1; // increase feet by 1
}
temp.feet += feet + d2.feet; // add the feet
return temp;
} 43
O f 3 3
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 44/70
Returning Objects from Functions (3/3)
int main()
{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
// display all lengths
cout << "\ndist1 = " ; dist1.showdist();
cout << "\ndist2 = " ; dist2.showdist();
cout << "\ndist3 = " ; dist3.showdist();
cout << endl;return 0;
}
44
R i Obj f F i
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 45/70
Returning Objects from Functions
To execute the statement dist3 = dist1.add_dist(dist2);
A temporary object of class Distance is 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 feet and
inches.
The second is the object passed as an argument, dist2.
Its member data is accessed as d2.feet and d2.inches.
The result is stored in temp and accessed as temp.feet
and temp.inches.
45
R i Obj f F i
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 46/70
Returning Objects from Functions
The temp object is then returned by the function using
the statement return temp;
The statement in main() assigns it to dist3.
Notice that dist1 is not modified; it simply supplies data
to add_dist(). Figure 6.7 shows how this looks.
In Chapter 8, “Operator Overloading” we’ll see how to
use the arithmetic + operator to achieve the even more
natural expression dist3 = dist1 + dist2;
46
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 47/70
47
10
8
11
6.25
22
2.25
St t d Cl
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 48/70
Structures and Classes
In fact, you can use structures in almost exactly the same
way that you use classes. The only formal differencebetween class and struct is 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
class foo
{
int data1; public:
void func();
}; //and the data1 will still be private.
48
St t d Cl
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 49/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
struct foo{void func();
private:
int data1;
}; // since public is the default.
However, in most situations programmers don’t use a
struct this way. They use structures to group only data,
and classes to group both data and functions.49
Cl Obj t d M
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 50/70
Classes, Objects and Memory
you might have the impression that each object created
from a class contains separate copies of that class’s data and member functions.
It’s true that each object has its own separate data items
But all the objects in a given class use the same member functions.
The member functions are created and placed in memory
only once—when they are defined in the class definition.
Since the functions for each object are identical. The data
items, however, will hold different values.
50
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 51/70
51
St ti Cl D t
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 52/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 manyobjects 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 conti-
nues to exist even if there are no objects of 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.52
U f Stati Cla Data
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 53/70
Uses of Static Class Data
Why would you want to use static member data? As an
example, suppose an object needed to know how many other 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 static variable Total_Cars could 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 of Total_Cars.
53
Static Data Class (1/2)
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 54/70
Static Data Class (1/2)
// statdata.cpp demonstrates a simple static data member
#include <iostream> using namespace std;
class Car{
private:
static int Total_Cars; // only one data item for all objects
// note: "declaration" only! public:
Car() // increments count when object created
{ Total_Cars++; }
int How_Many() // returns count
{ return Total_Cars; }~Car()
{ Total_Cars--; }
};
int Car::Total_Cars = 0; // *definition* of count
54
Static Data Class (2/2)
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 55/70
Static Data Class (2/2)
int main(){
Car Toyota, Honda, Suzuki; // create three objects
cout << Toyota.How_Many() << " Cars are in Race" << endl;
cout << Honda.How_Many() << " Cars are in Race" << endl;
// each object sees the same datacout << Suzuki.How_Many() << " Cars are in Race" << endl;
Car *Pajero = new Car;
cout << Suzuki.How_Many() << " Cars are in Race" << endl;
delete Pajero;
cout << Honda.How_Many() << " Cars are in Race" << endl;
return 0;
}
55
Static Class Data (S t D l ti d D fi iti )
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 56/70
Static Class Data (Separate Declaration and Definition)
Ordinary variables are 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 variable’s declaration appears in the class definition,
but the variable is actually defined outside the class, in much
the same way as a global variable. If static member 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.56
const Members Functions
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 57/70
const Members Functions
A const member function guarantees that it will never
modify any of its class’s member data.
57
//constfu.cpp demonstrates const member functions
class aClass
{
private:int alpha;
public:
void nonFunc() // non-const member function
{ alpha = 99; } // OK
void conFunc() const // const member function
{ alpha = 99; } // ERROR: can’t modify a member
};
Distance Class and Use of const (1/3)
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 58/70
Distance Class and Use of const (1/3)
// const member functions & const arguments to member functions
#include <iostream> using namespace std;
class Distance{ // English Distance class
private:
int feet;
float inches; public: // constructor (no args)
Distance() : feet(0), inches(0.0)
{ } // constructor (two args)
Distance(int ft, float in) : feet(ft), inches(in)
{ }void getdist(){ // get length from user
cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
58
Distance Class and Use of const (2/3)
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 59/70
Distance Class and Use of const (2/3)
void showdist() const // display distance
{ cout << feet << "\'-" << inches << '\"'; }Distance add_dist(const Distance&) const; //add
};
//add this distance to d2, return the sum
Distance Distance::add_dist(const Distance& d2) const{
Distance temp; // temporary variable// feet = 0; // ERROR: can’t modify this
// d2.feet = 0; // ERROR: can’t modify d2
temp.inches = inches + d2.inches; // add the inches
if(temp.inches >= 12.0) // if total exceeds 12.0,
{ temp.inches -= 12.0; // then decrease inches by 12.0temp.feet = 1; // and increase feet
} // by 1
temp.feet += feet + d2.feet; // add the feet
return temp;
} 59
Distance Class and Use of const (3/3)
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 60/70
Distance Class and Use of const (3/3)
int main()
{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
//display all lengths
cout << "\ndist1 = "; dist1.showdist();
cout << "\ndist2 = "; dist2.showdist();
cout << "\ndist3 = "; dist3.showdist();
cout << endl;return 0;
}
60
const Member Function Arguments
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 61/70
const Member Function Arguments
if an argument is passed to an ordinary function by
reference, and you don’t 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(const Distance& d2) const{
In above line, argument to add_dist() is passed by
reference, and we want to make sure that won’t modify
this variable, which is dist2 in main(). Therefore we make
the argument d2 to add_dist() const in both declaration
and definition.
61
const Objects
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 62/70
const Objects
In several example programs, we’ve seen that we can
apply const to variables of basic types such as int to keepthem from being modified.
In a similar way, we can apply const to objects of classes.
When an object is declared as const, you can’t modify it.
It follows that you can use only const member functions
with it, because they’re 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.62
const Objects (1/2)
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 63/70
const Objects (1/2)
// constObj.cpp constant Distance objects
#include <iostream> using namespace std;
class Distance // English Distance class
{
private:
int feet;float inches;
public: // 2-arg constructor
Distance(int ft, float in) : feet(ft), inches(in)
{ }
void getdist() // user input; non-const func{
cout << "\nEnter feet:" ; cin >> feet;
cout << "Enter inches:" ; cin >> inches;
}
63
const Objects (2/2)
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 64/70
const Objects (2/2)
void showdist() const // display distance; const func
{cout << feet << "\'-" << inches << '\"';
}
};
int main(){
const Distance football(300, 0);
// football.getdist(); // ERROR: getdist() not const
cout << "football = " ;
football.showdist(); // OKcout << endl;
return 0;
}
64
Assignment Number 1 Question 1
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 65/70
Assignment Number 1 Question 1
Create a class called time
that has separate int member data for hours, minutes, andseconds.
One constructor should 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, minute and seconds respectively.
65
Assignment Number 1 Question 1
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 66/70
Assignment Number 1 Question 1
include a tick member function that increments the
time stored in a Time object by one second. An add member 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 printTime
functions in that loop for an object. Also make two objects and
add them to a third object and print their values.
66
Assignment Number 1 Question 2
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 67/70
Assignment Number 1 Question 2
Create a class called date
that has separate int member data for year, month, and day. One constructor should initialize this date to 20-02-2010, and
another constructor should initialize it to fixed values given by user.
Make void print() to display date in dd-mm-yyyy format.
Make void setDate( int, int, int ) to set day, month, year perform error checking while setting the values for data members
month, day and year.
Make void nextDay() to increment the day by one.
Be sure to test the following cases:
Incrementing into the next month.
Incrementing into the next year.
in main() test function nextDay in a loop that prints the date during
each iteration to illustrate that nexTDay works correctly.67
Assignment Number 1 Question 3
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 68/70
Assignment Number 1 Question 3
Create a class called Rational for performing arithmetic
with fractions. Write a program to test your class. Use integer variables to represent the private data of
the class the numerator and the denominator.
Provide a constructor that 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/4 would be stored in theobject as 1 in the numerator and 2 in the denominator.
Provide public member functions that perform each of
the following tasks:68
Assignment Number 1 Question 3
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 69/70
Assignment Number 1 Question 3
1. Adding two Rational numbers. The result should be
stored in reduced form.2. Subtracting two Rational numbers. The result should
be stored in reduced form.
3. Multiplying two Rational numbers. The result shouldbe stored in reduced form.
4. Dividing two Rational numbers. The result should be
stored in reduced form.
5. Printing Rational numbers in the form a/b, where a is
the numerator and b is the denominator.
6. Printing Rational numbers in floating-point format.
69
Assignment Number 1 Question 4
7/31/2019 Ch06 Objects and Classes (1)
http://slidepdf.com/reader/full/ch06-objects-and-classes-1 70/70
Assignment Number 1 Question 4
Implement a Circle class. Each object of this class will
represent a circle, storing its radius and the x and y coordinates of its center as floats.
One constructor should 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 return area and circumference.
Make void print() function to display xy coordinates and
radius of a circle.
Call these functions in main() to display their working.