Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

02.objects and Classes

Uploaded by

iqraqui
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

02.objects and Classes

Uploaded by

iqraqui
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Object Class

Object Oriented Programming


Objects and Classes
1
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
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
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
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.

functions data

A class encapsulates
attributes and functions

5
Example 1: A Simple Class
#include <iostream>
#include <stdlib.h>
using namespace std;

class student { // define a class (a int main() {


concept) student Ali, Usman; // define two
objects
private: // of class student
int age; // class data (attributes) Ali.set_age(21); // call member
function
public: Usman.set_age(18); // to set age
void set_age(int g) { // member
function Ali.show_age(); // call member
age = g; // to set age function
} Usman.show_age(); // to display age
void show_age() { // member system("PAUSE");
function return 0;
// to display }
age
cout << "I am " << age
6
<< " Years Old."<< endl;
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 Corolla is an
instance of a vehicle.
 In the program the class , whose name is student, is defined in the first part of
the program.
 In main(), we define two objects Ali and Usman that are instances of that class.
 Each of the two objects is given a value, and each displays its value.

7
Defining the Class

Syntax for class definition 8


Defining the Class
 The definition starts with the keyword class, followed by the class name—
student 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 a variable 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.

9
Defining the Class
 private data or functions can only be accessed from within the class.
 public data or functions, on the other hand, are accessible from outside the
class.
 The data member age follows the keyword private, so it can be accessed from
within the class, but not from outside.
 Member functions (also called methods or messages) are functions that are
included within a class.
 There are two member functions in student class:
set_age() and show_age().

10
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.

11
Defining the Class
 Remember that the definition of the class student 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 is created. An object is an instance of a class.
 ali.set_age(21); This syntax is used to call a member function that is
associated with a specific object ali.
 Member functions of a class can be accessed only by an object of that class.

12
Example 2: Using Mobile Phone as an Object (1/2)
// mobile.cpp demonstrates mobile phone as an object

#include <iostream>
#include <stdlib.h>
using namespace std;
class mobile // class name should be
{ // the name of a concept
private:
string company_name;
string model_number;
string emi_number;
float cost;
public:

void set_info(string cn, string mn, string emi, float price) { // set data
company_name = cn;
model_number = mn;
emi_number = emi;
cost = price;
}
13
Example 2: Using Mobile Phone as an Object (2/2)
void show_info()
{ // display data
cout << "Company = " << company_name << endl;
cout << "Model = " << model_number << endl;
cout << "EMI = " << emi_number << endl;
cout << "Cost = Rs." << cost << endl;
}
};

int main(){
mobile m1; // define object of class part
// call member function set_nfo()
m1.set_info("QMobile", "Noir A950", "dont know :)", 25000.0F);

// now call member function show_info()


m1.show_info();
system("PAUSE");
return 0;
}
14
Using Mobile Phone as an Object
 If you were designing an inventory program you might actually want to create
a class something like mobile.
 It’s an example of a C++ object representing a physical object in the real world
—a mobile phone.
 Standard C++ includes a new class called string.
 Using string object, 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.

15
Example 3: Using Class to Represent Height (1/2)
#include <iostream>
#include <stdlib.h>
using namespace std;
class Height{ // A Height class
private:
int feet; float inches;
public:
void set(int ft, float in){
feet = ft; inches = in;
}
void get(){ // get height information from user
cout << "\nEnter Your Height Information "<<endl;
cout << "Enter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
void show(){ // display height information
cout << "Height = "<< feet << " feet and " << inches
<< " inches."<<endl;
}
};
16
Example 3: Using Class to Represent Height (2/2)
int main()
{
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 << "For H1, "; H1.show();
cout << "For H2, "; H2.show();

system("PAUSE");
return 0;
}

17
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.

18
Example 4: Constructors A House Example (1/2)
#include <iostream> // A Constructor Example
#include <stdlib.h>
using namespace std;
class House{
private:
double area; // area in square feet
public:
House() : area(1000){ /* a zero (no) argument constructor */
cout<< "A House Created \n"; /* */
} /* */
void set_area(double a)
{ area = a; }
double return_area()
{ return area; }
void get_area(){ // get area info from user
cout << "What is the area of House in Square Feet:";
cin >> area;
}
};
19
Example 4: Constructors A House Example (2/2)
int main()
{
House H1, H2; /* define two objects and call constructor */
cout << "default area of House H1 is = "
<< H1.return_area() << endl;
cout << "default area of House H2 is = "
<< H2.return_area() << endl;
H1.set_area(1500);
H2.get_area();
cout << "Now Area of House H1 is = "
<< H1.return_area() << " Square Feet"<<endl;
cout << "Now Area of House H2 is = "
<< H2.return_area() << " Square Feet"<<endl;

system("PAUSE");
return 0;
}

20
Example 5: Constructors A Dice Example (1/2)
#include <iostream> // for cin and cout
#include <stdlib.h> // for rand(), srand() and system()
#include <time.h> // for time()
using namespace std;
class Dice{
private:
int number;
public:
Dice():number(1){ /* A 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)); /* Seed with Current time of PC */
} /* */
int roll() // 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;
return number;
}
21
Example 5: Constructors A Dice Example (2/2)
int get_number() // Function to return the number on the top face
{ // of the die. It returns the value of the variable number.
return number;
}
};

int main(){
Dice d1,d2;
cout << "d1: " << d1.get_number() << endl;
cout << "d2: " << d2.get_number() << endl;
cout << "After rolling d1: " << d1.roll() << endl;
cout << "After rolling d2: " << d2.roll() << endl;
cout << "The sum of the numbers rolled by the dice is: "
<< d1. get_number() + d2. get_number() << endl;
cout << "After rolling again, the sum of the numbers rolled is: "
<< d1.roll() + d2.roll() << endl;
system("PAUSE");
return 0;
}
22
Example: Multi-Argument Constructor (1/2)
// mobile.cpp demonstrates mobile phone as an object

#include <iostream>
#include <stdlib.h>
using namespace std;
class mobile // class name should be
{ // the name of a concept
private:
string company_name;
string model_number;
string emi_number;
float cost;
public:

mobile (string cn, string mn, string emi, float price) { // set data
company_name = cn;
model_number = mn;
emi_number = emi;
cost = price;
}
23
Example: Multi-Argument Constructor (2/2)
void show_info()
{ // display data
cout << "Company = " << company_name << endl;
cout << "Model = " << model_number << endl;
cout << "EMI = " << emi_number << endl;
cout << "Cost = Rs." << cost << endl;
}
};

int main(){
mobile m1("QMobile", "Noir A950", "dont know :)", 25000.0F);

// now call member function show_info()


m1.show_info();
system("PAUSE");
return 0;
}

24
Destructor
 You might guess that another function is called automatically
when an object is destroyed.
 This is indeed the 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.
 There cannot be more than one destructor in a class.
 The most common use of destructors is to de-allocate memory that was
allocated for the object by the constructor.
25
Example 6: Destructor A House Example (1/2)
#include <iostream>
using namespace std;
class House{
private: double area; // area in square feet
public:
House() : area(1000) // a zero argument const.
{ cout << "House Created \n"; }
House(double a) : area(a) // a 1 argument const.
{ cout << “A House Created \n"; }
~House() // A Destructor
{ cout<< "House has been destroyed \n"; }
double return_area()
{ return area; }
};
int main(){
House H1 , H2(600.0);
cout << "Area of "
<< "House H1 is = " << H1.return_area() << endl
<< "House H2 is = " << H2.return_area() << endl;
system("PAUSE"); return 0; }
26
Example 7: Destructor A House Example (1/2)
// A Constructor Example
#include <iostream>
using namespace std;
class House{
private: double area; // Area in square feet
public:
House() : area(1000) // A zero (no) argument constructor
{ cout << "House Created \n"; }
~House() // A Destructor
{ cout << "House has been destroyed \n"; }
};
void Create_House(){
House aHouse;
cout << "End of function" << endl;
}
int main(){
Create_House();
Create_House();
system("PAUSE"); return 0;
}
27
Example 8: Destructor A Student Example (1/3)
#include <iostream>
#include <cstring> // for calling strlen() function
using namespace std;
class Student {
public:
char* name; // A pointer to store address of a string
int length; // to store length of a String
Student() : length(100) { // Make a zero (no) argument constructor and set length =
100
name = new char[length + 1]; // request 101 bytes memory to OS
cout << "No Argument Constructor was called" << endl;
}
Student(const char* src) {// Make a one argument constructor
length = strlen(src) ; // find length of src string
cout << "Requesting "<< length+1 <<" bytes more Memory to OS" << endl;
name = new char[length+1]; // assign memory to name pointer one extra byte is for
NULL
strcpy_s(name, length+1, src); // copy string from src to name 28
Example 8: Destructor A String Example (2/3)
~Student() { /* A destructor */
cout << "Object is Destroyed / Deleted " << endl;
cout << "Therefore returning " << length + 1 <<" bytes Memory to OS\n" << endl;
delete[] name; /* return occupied memory to OS */
}

void Show_Name(){
cout << name << endl;
}

void Get_Name(){
cout << "Enter Name:";
cin.get(name, length + 1); fflush(stdin);
}

};

29
Example 8: Destructor A String Example (3/3)
int main() {
Student* s1 = new Student("Rashid Farid");
s1->Show_Name();
s1->Get_Name();
s1->Show_Name();
delete s1;
system("PAUSE");
return 0;
}

30
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.
31
Example 9: Objects As Function Arguments (1/3)
// englcon.cpp constructors, adds objects using member function
#include <iostream>
#include <stdlib.h>
using namespace std;
class Distance // English Distance class
{
private:
int feet; float inches;

public:
Distance() : feet(0), inches(0.0)
{ 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 value of feet and inches from user


cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
32
Example 9: Objects As Function Arguments (2/3)
void showDist(){ // display distance
cout << feet << "\'-" << inches << '\"';
}

void addDist( Distance, Distance ); // declaration


};

// member function is defined outside the class

void Distance::addDist(Distance d1, Distance d2)


{
inches = d1.inches + d2.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
}
feet += d1.feet + d2.feet; // add the feet
}
33
Example 9: Objects As Function Arguments (3/3)
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.addDist(dist1, dist2); // dist3 = dist1 + dist2
// display all lengths
cout << "\ndist1 = "; dist1.showDist();
cout << "\ndist2 = "; dist2.showDist();
cout << "\ndist3 = "; dist3.showDist();
cout << endl;
system("PAUSE");
return 0;
}

34
Constructors Overloading
 Since there are now two explicit constructors with the same name,
Distance(), we say the constructor is overloaded.
 Which of the two constructors is executed when an object is created depends
on how many arguments are used in the definition:

Distance length;
// calls first constructor

Distance width(11, 6.0);


// calls second constructor
35
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.
36
Objects as Arguments
 Since add_dist() is a member function of the Distance class, it can access the
private data in any object of class Distance 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.

37
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), the function 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 the dot operator (dist1.inches or dist2.feet) to
other objects of the same class that are passed as arguments.

38
Objects as Arguments
21

1.75

9 11

7.5
6.25

39
The Default Copy Constructor
 We’ve 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 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.

40
Example 10: The Default Copy Constructor (1/2)
// ecopycon.cpp initialize objects using default copy constr.
#include <iostream>
#include <stdlib.h>
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 value of feet and inches from user


cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
41
Example 10: 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 constructor
Distance dist3(dist2); // calls default copy constructor
Distance dist4 = dist2; // also calls default copy const.
cout << "\ndist1 = "; dist1.showdist(); // display all lengths
cout << "\ndist2 = "; dist2.showdist();
cout << "\ndist3 = "; dist3.showdist();
cout << "\ndist4 = "; dist4.showdist();
cout << endl;
system("PAUSE");
return 0;
}

42
Example 11: Returning Objects from Functions (1/3)
// englret.cpp function returns value of type Distance
#include <iostream>
#include <stdlib.h>
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 value of feet and inches from user


cout << "Enter feet : "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
43
Example 11: Returning Objects from Functions (2/3)
void showdist() // display feet'-inches"
{ cout << feet << "\'-" << inches << '\"'; }

Distance add_dist(Distance); // function declaration

};

// add this distance to d2 and return the sum using temp object
Distance Distance::add_dist(Distance d2){ // function definition
Distance temp; // temporary objet
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; // return value of temporary objet
}

44
Example 11: 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

cout << "\ndist1 = " ; dist1.showdist(); // display all lengths


cout << "\ndist2 = " ; dist2.showdist();
cout << "\ndist3 = " ; dist3.showdist();
cout << endl;
system("PAUSE");
return 0;
}

45
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. Its member

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.
 The temp object is then returned by the function using the statement return
temp;
 The statement in main() assigns it to dist3.
46
Returning Objects from Functions
 Notice that dist1 is not modified; it simply supplies data to add_dist().
 Figure on next slide shows how this looks.
 In the topic, “Operator Overloading”, we’ll see how to use the arithmetic +
operator to achieve the even more natural expression like dist3 = dist1 + dist2;

47
Returning Objects from Functions
22

2.25

10 11

8 6.25

48
Structures and Classes
 In fact, you can use structures in almost exactly the same way that you use
classes. The only formal difference between 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.

49
Structures and Classes
 If you want to use a structure to accomplish the same thing as this class, you
can dispense with the keyword public, 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.
50
Classes, Objects and Memory
 You might have the impression that each object Object
1
Object
2
Object
3

created from a class contains separate copies of data1 data1 data1

that class’s data and member functions. data2 data2 data2


 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. Function1()

 Since the functions for each object are identical. Function2()

The data items, however, will hold different values.


51
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.
 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
static Data in a Class
 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
Example 12: static Data in a Class (1/2)
// statdata.cpp demonstrates a simple static data member
#include <iostream>
#include <stdlib.h>
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--; } // decrement count when an object is destroyed

};
int Car::Total_Cars = 0; // initialization of count
54
Example 12: static Data in a 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 data
cout << Suzuki.How_Many() << " Cars are in Race" << endl;

Car *Pajero = new Car; // create a nameless objet and store


// its starting address in a pointer p

cout << Suzuki.How_Many() << " Cars are in Race" << endl;
cout << Pajero->How_Many() << " Cars are in Race" << endl;

delete Pajero;

cout << Honda.How_Many() << " Cars are in Race" << endl;
system("PAUSE");
return 0;
}
55
static Members Data
 Ordinary variables are usually declared (the compiler is told about their name
and type) and defined (the compiler 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
Example 13: const Member Function
 A const member function guarantees that it will never modify any of its class’s
member data.
//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
}
};
57
Example 14: 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; // attributes
public:
Distance() : feet(0), inches(0.0)
{ } // constructor (no args)

Distance(int ft, float in) : feet(ft), inches(in)


{ } // constructor (two args)

void getdist(){ // get value of feet and inches from user


cout << "\nEnter feet: "; cin >> feet;
cout << "Enter inches: "; cin >> inches;
}
58
Example 14: Distance Class and Use of const (2/3)
void showdist() const // display distance
{ cout << feet << "\'-" << inches << '\"'; }
Distance add_dist(const Distance&) const; // add two objects
};

//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.0
temp.feet += 1; // and increase feet by 1
}
temp.feet += feet + d2.feet; // add the feet
return temp; // return temp object
}
59
Example 14: 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;
system("PAUSE");
return 0;
}

60
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
 In several example programs, we’ve seen that we can apply const to variables
of basic types such as int to keep them 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 the length
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
Example 15: 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:

Distance(int ft, float in) : feet(ft), inches(in)


{ } // 2-arg constructor

void getdist() // user input; non-const function


{
cout << "\nEnter feet:" ; cin >> feet;
cout << "Enter inches:" ; cin >> inches;
}

63
Example 15: const Objects (2/2)
void showdist() const // display distance; const function
{
cout << feet << "\'-" << inches << '\"';
}
};

int main()
{
const Distance football(300, 0);

// football.getdist(); // ERROR: getdist() not const

cout << "football = " ;


football.showdist(); // OK
cout << endl;
system("PAUSE");
return 0;
}

64
Thank you

65

You might also like