View
224
Download
1
Tags:
Embed Size (px)
Citation preview
A Deeper Look at Classes
CS-2303, C-Term 2010 1
A Deeper Look at Classes
CS-2303System Programming Concepts
(Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie and from C: How to Program, 5th and 6th editions, by Deitel and Deitel)
A Deeper Look at Classes
CS-2303, C-Term 2010 2
const (Constant) Objects andconst Member Functions
• Principle of Least Privilege – “Allow access to data only when absolutely needed”– Fundamental principle of good software engineering
• const objects– Keyword const– Specifies that an object is not modifiable – Attempts to modify const object compilation errors
• Example– const Time noon (12, 0, 0);
A Deeper Look at Classes
CS-2303, C-Term 2010 3
const Member Functions
• Only const member functions can be called for const objects
• Member functions declared const may not modify the object in any way
• A function is specified as const both prototype and definition.
• Constructors and destructors are not const – By definition!
A Deeper Look at Classes
CS-2303, C-Term 2010 4
1 // Fig. 21.1: Time.h
2 // Definition of class Time.
3 // Member functions defined in Time.cpp.
4 #ifndef TIME_H
5 #define TIME_H
6
7 class Time
8 {
9 public:
10 Time( int = 0, int = 0, int = 0 ); // default constructor
11
12 // set functions
13 void setTime( int, int, int ); // set time
14 void setHour( int ); // set hour
15 void setMinute( int ); // set minute
16 void setSecond( int ); // set second
17
18 // get functions (normally declared const)
19 int getHour() const; // return hour
20 int getMinute() const; // return minute
21 int getSecond() const; // return second
const Example
A promise that these functionsdo not modify the object at all
A Deeper Look at Classes
CS-2303, C-Term 2010 5
22
23 // print functions (normally declared const)
24 void printUniversal() const; // print universal time
25 void printStandard(); // print standard time (should be const)
26 private:
27 int hour; // 0 - 23 (24-hour clock format)
28 int minute; // 0 - 59
29 int second; // 0 - 59
30 }; // end class Time
31
32 #endif
const Example (continued)
Same here!
A Deeper Look at Classes
CS-2303, C-Term 2010 6
1 // Fig. 21.2: Time.cpp
2 // Member-function definitions for class Time.
3 #include <iostream>
4 using std::cout;
5
6 #include <iomanip>
7 using std::setfill;
8 using std::setw;
9
10 #include "Time.h" // include definition of class Time
11
12 // constructor function to initialize private data;
13 // calls member function setTime to set variables;
14 // default values are 0 (see class definition)
15 Time::Time( int hour, int minute, int second )
16 {
17 setTime( hour, minute, second );
18 } // end Time constructor
19
20 // set hour, minute and second values
21 void Time::setTime( int hour, int minute, int second )
22 {
23 setHour( hour );
24 setMinute( minute );
25 setSecond( second );
26 } // end function setTime
const Example (continued)
Not co
nst
A Deeper Look at Classes
CS-2303, C-Term 2010 7
27
28 // set hour value
29 void Time::setHour( int h )
30 {
31 hour = ( h >= 0 && h < 24 ) ? h : 0; // validate hour
32 } // end function setHour
33
34 // set minute value
35 void Time::setMinute( int m )
36 {
37 minute = ( m >= 0 && m < 60 ) ? m : 0; // validate minute
38 } // end function setMinute
39
40 // set second value
41 void Time::setSecond( int s )
42 {
43 second = ( s >= 0 && s < 60 ) ? s : 0; // validate second
44 } // end function setSecond
45
46 // return hour value
47 int Time::getHour() const // get functions should be const
48 {
49 return hour;
50 } // end function getHour
const keyword in function definition, as well as in function prototype
const Example (continued)
A Deeper Look at Classes
CS-2303, C-Term 2010 8
51
52 // return minute value
53 int Time::getMinute() const
54 {
55 return minute;
56 } // end function getMinute
57
58 // return second value
59 int Time::getSecond() const
60 {
61 return second;
62 } // end function getSecond
63
64 // print Time in universal-time format (HH:MM:SS)
65 void Time::printUniversal() const
66 {
67 cout << setfill( '0' ) << setw( 2 ) << hour << ":"
68 << setw( 2 ) << minute << ":" << setw( 2 ) << second;
69 } // end function printUniversal
70
71 // print Time in standard-time format (HH:MM:SS AM or PM)
72 void Time::printStandard() // note lack of const declaration
73 {
74 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
75 << ":" << setfill( '0' ) << setw( 2 ) << minute
76 << ":" << setw( 2 ) << second << ( hour < 12 ? " AM" : " PM" );
77 } // end function printStandard
const Example (continued)
Same here!
And here!
A Deeper Look at Classes
CS-2303, C-Term 2010 9
Purpose of const
• To enlist the aid of the compiler in detecting unwanted changes to objects
• Widely used in large programming projects
• Helps maintain sanity, teamwork, etc.
A Deeper Look at Classes
CS-2303, C-Term 2010 11
Default Memberwise Assignment
• Assignment operator (=)– Can be used to assign an object to another object of the
same type.• Each data member of the right object is assigned to the same
data member in the left object.
• Not usually want you want to do!– Often causes serious problems when data members
contain pointers to dynamically allocated memory !!• Because pointers are simply copied
Deitel & Deitel, §20.10
A Deeper Look at Classes
CS-2303, C-Term 2010 12
1 // Fig. 20.17: Date.h
2 // Declaration of class Date.
3 // Member functions are defined in Date.cpp
4
5 // prevent multiple inclusions of header file
6 #ifndef DATE_H
7 #define DATE_H
8
9 // class Date definition
10 class Date
11 {
12 public:
13 Date( int = 1, int = 1, int = 2000 ); // default constructor
14 void print();
15 private:
16 int month;
17 int day;
18 int year;
19 }; // end class Date
20
21 #endif
Default initialization of data members
Default Memberwise Assignment – Example
A Deeper Look at Classes
CS-2303, C-Term 2010 13
1 // Fig. 20.18: Date.cpp
2 // Member-function definitions for class Date.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 #include "Date.h" // include definition of class Date from Date.h
8
9 // Date constructor (should do range checking)
10 Date::Date( int m, int d, int y )
11 {
12 month = m;
13 day = d;
14 year = y;
15 } // end constructor Date
16
17 // print Date in the format mm/dd/yyyy
18 void Date::print()
19 {
20 cout << month << '/' << day << '/' << year;
21 } // end function print
Default Memberwise Assignment (continued)
A Deeper Look at Classes
CS-2303, C-Term 2010 14
1 // Fig. 20.19: fig20_19.cpp
2 // Demonstrating that class objects can be assigned
3 // to each other using default memberwise assignment.
4 #include <iostream>
5 using std::cout;
6 using std::endl;
7
8 #include "Date.h" // include definition of class Date from Date.h
9
10 int main()
11 {
12 Date date1( 7, 4, 2004 );
13 Date date2; // date2 defaults to 1/1/2000
14
15 cout << "date1 = ";
16 date1.print();
17 cout << "\ndate2 = ";
18 date2.print();
19
20 date2 = date1; // default memberwise assignment
21
22 cout << "\n\nAfter default memberwise assignment, date2 = ";
23 date2.print();
24 cout << endl;
25 return 0;
26 } // end main date1 = 7/4/2004 date2 = 1/1/2000 After default memberwise assignment, date2 = 7/4/2004
memberwise assignment assigns
data members of date1 to date2
date2 now stores the
same date as date1
Default Memberwise Assignment (continued)
A Deeper Look at Classes
CS-2303, C-Term 2010 15
Default Memberwise Assignment (concluded)
• Many classes must provide their own assignment operator
• To intelligently assign one object to another
• More about assignment of objects to each other when we get to Operator Overloading
• The '=' operator can be overloaded, just like any other
A Deeper Look at Classes
CS-2303, C-Term 2010 16
Copy Constructor
• A constructor that copies another object of the same type
• Example:–class TreeNode {public:... /* other methods */TreeNode(const TreeNode &nodeToBeCopied);
// Copy Constructorprivate:const string word;int count;TreeNode *left, *right;
};
A Deeper Look at Classes
CS-2303, C-Term 2010 17
Default Copy Constructor
• Compiler provides a default copy constructor– Copies each member of the original object into the
corresponding member of the new object– i.e., memberwise assignment
• Enables pass-by-value for objects– Used to copy original object’s values into new object to
be passed to a function or returned from a function
• Not usually want you want to do!– Often causes serious problems when data members
contain pointers to dynamically allocated memory !!• Just like default memberwise assignment
A Deeper Look at Classes
CS-2303, C-Term 2010 18
Copy Constructor
• Many classes must provide an explicit Copy Constructor
• To intelligently copy one object to another
• Example:–string(const string &stringToBeCopied);
• Allocates new memory for the new string
• Copies characters from one to other
• Does not blindly copy members (include internal pointers, etc.)
Why do we need '&'?
A Deeper Look at Classes
CS-2303, C-Term 2010 19
Usage of Copy Constructor
• In Initializer list• Example:–TreeNode::TreeNode(const string &newWord):word(newWord), //initialize wordcount(1), //initialize countleft(NULL),right(NULL)
{
/* rest of constructor body */
} // TreeNode constructor
The string copy constructor
A Deeper Look at Classes
CS-2303, C-Term 2010 22
Ordinary Member Functions
1. Function can access the private members of the class
2. Function is in the scope of the class
3. Function must be invoked on a specific object of the class – e.g.,• ptr -> func()• obj.func()
A Deeper Look at Classes
CS-2303, C-Term 2010 23
static Member Function
1. Function can access the private members of the class
2. Function is in the scope of the class
3. Function must be invoked on a specific object of the class – e.g.,• ptr -> func()• obj.func()
• But only the static members• Members that exist independently of any objects
A Deeper Look at Classes
CS-2303, C-Term 2010 24
friend Function
1. Function can access the private members of the class
2. Function is in the scope of the class
3. Function must be invoked on a specific object of the class – e.g.,• ptr -> func()• obj.func()
A Deeper Look at Classes
CS-2303, C-Term 2010 25
friend Function of a Class
• Defined outside that class’s scope.
• Not a member function of that class.
• Has right to access non-public and public members of that class.
• Often appropriate when a member function cannot be used for certain operations.
• Can enhance performance.
Deitel & Deitel, §21.4
A Deeper Look at Classes
CS-2303, C-Term 2010 26
friend Functions and friend Classes
• To declare a function as a friend of a class:–– Provide the function prototype in the class definition
preceded by keyword friend
• To declare a class as a friend of another class:– Place a declaration of the form– friend class ClassTwo;
in the definition of class ClassOne
• All member functions of class ClassTwo are friends of class ClassOne
A Deeper Look at Classes
CS-2303, C-Term 2010 27
friend Functions and friend Classes(continued)
• Friendship is granted, not taken.– For class B to be a friend of class A, class A must
explicitly declare that class B is its friend.
• Friendship relation is neither symmetric nor transitive– If class A is a friend of class B, and class B is a
friend of class C, cannot infer that • class B is a friend of class A, • class C is a friend of class B, • class A is a friend of class C.
• …
A Deeper Look at Classes
CS-2303, C-Term 2010 28
friend Functions and friend Classes(continued)
• …
• It is possible to specify overloaded functions as friends of a class.– Each overloaded function intended to be a friend must be explicitly declared as a friend of the class.
A Deeper Look at Classes
CS-2303, C-Term 2010 29
1 // Fig. 21.15: fig21_15.cpp
2 // Friends can access private members of a class.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 // Count class definition
8 class Count
9 {
10 friend void setX( Count &, int ); // friend declaration
11 public:
12 // constructor
13 Count()
14 : x( 0 ) // initialize x to 0
15 {
16 // empty body
17 } // end constructor Count
18
19 // output x
20 void print() const
21 {
22 cout << x << endl;
23 } // end function print
24 private:
25 int x; // data member
26 }; // end class Count
friend function declaration (can appear anywhere in the class)
friend Function Example
A Deeper Look at Classes
CS-2303, C-Term 2010 30
27
28 // function setX can modify private data of Count
29 // because setX is declared as a friend of Count (line 10)
30 void setX( Count &c, int val )
31 {
32 c.x = val; // allowed because setX is a friend of Count
33 } // end function setX
34
35 int main()
36 {
37 Count counter; // create Count object
38
39 cout << "counter.x after instantiation: ";
40 counter.print();
41
42 setX( counter, 8 ); // set x using a friend function
43 cout << "counter.x after call to setX friend function: ";
44 counter.print();
45 return 0;
46 } // end main counter.x after instantiation: 0 counter.x after call to setX friend function: 8
friend function can modify Count’s private data
Calling a friend function; note that we pass the Count object to the function
friend Function Example (continued)
A Deeper Look at Classes
CS-2303, C-Term 2010 32
The this Pointer
• Member functions know which object’s data members to manipulate
• Every object has access to its own address through a pointer called this (a C++ keyword)
• An object’s this pointer is not part of the object itself
• The this pointer is passed (by the compiler) as an implicit argument to each of the object’s non-static member functions
A Deeper Look at Classes
CS-2303, C-Term 2010 33
Using the this Pointer
• Objects may use the this pointer implicitly or explicitly.
• this is used implicitly when accessing members directly.
• It is used explicitly when using keyword this.
• Type of the this pointer depends on – type of the object, and – whether member function is declared const.
A Deeper Look at Classes
CS-2303, C-Term 2010 34
1 // Fig. 21.17: fig21_17.cpp
2 // Using the this pointer to refer to object members.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 class Test
8 {
9 public:
10 Test( int = 0 ); // default constructor
11 void print() const;
12 private:
13 int x;
14 }; // end class Test
15
16 // constructor
17 Test::Test( int value )
18 : x( value ) // initialize x to value
19 {
20 // empty body
21 } // end constructor Test
this Example
A Deeper Look at Classes
CS-2303, C-Term 2010 35
22
23 // print x using implicit and explicit this pointers;
24 // the parentheses around *this are required
25 void Test::print() const
26 {
27 // implicitly use the this pointer to access the member x
28 cout << " x = " << x;
29
30 // explicitly use the this pointer and the arrow operator
31 // to access the member x
32 cout << "\n this->x = " << this->x;
33
34 // explicitly use the dereferenced this pointer and
35 // the dot operator to access the member x
36 cout << "\n(*this).x = " << ( *this ).x << endl;
37 } // end function print
38
39 int main()
40 {
41 Test testObject( 12 ); // instantiate and initialize testObject
42
43 testObject.print();
44 return 0;
45 } // end main x = 12 this->x = 12 (*this).x = 12
Implicitly using the this pointer to access member x
Explicitly using the this pointer to access member x
Using the dereferenced this pointer and the dot operator
this Example
A Deeper Look at Classes
CS-2303, C-Term 2010 36
Another Example Using this
class TreeNode {public:... /* other methods */TreeNode(const string &newWord,
TreeNode *parent); //constructor
private:const string word;int count;TreeNode *left, *rightTreeNode *const myParent;
};
A Deeper Look at Classes
CS-2303, C-Term 2010 37
Example Using this (continued)
TreeNode::TreeNode(const string &newWord, TreeNode *parent)
:word(newWord), //initialize wordcount(1), //initialize countleft(NULL),right(NULL),myParent(parent) //initialize myParent
{
/* rest of constructor body */
} // TreeNode constructor
A Deeper Look at Classes
CS-2303, C-Term 2010 38
Example Using this (continued)
TreeNode *TreeNode::AddNode(const string &newWord){if (newWord == word){
incr();return this;
}
else if (newWord < word) {if (left) return left->AddNode(newWord);else return left = new TreeNode(newWord,
this);} else {
/* same for right */}
} // AddNodeContructor of TreeNo
de with pointer
back to parent node!
A Deeper Look at Classes
CS-2303, C-Term 2010 39
Cascaded member-function calls
• Multiple functions are invoked in the same statement.
• Enabled by member functions returning the dereferenced this pointer.
• Example– t.setMinute( 30 ).setSecond( 22 );t.setMinute( 30 ).setSecond( 22 );
• Calls t.setMinute( 30 );t.setMinute( 30 );• Then calls t.setSecond( 22 );t.setSecond( 22 );
• See Deitel & Deitel, Figures 21.18–21.20
A Deeper Look at Classes
CS-2303, C-Term 2010 40
Questions?
New Programming Assignmentwill be posted this weekend!