more about c++ classescs-2303, c-term 20101 more about c++ classes cs-2303 system programming...
Post on 22-Dec-2015
215 views
TRANSCRIPT
More about C++ ClassesCS-2303, C-Term 2010 1
More about C++ 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)
More about C++ ClassesCS-2303, C-Term 2010 2
Reading Assignment
• Deitel & Deitel, 5th edition, Chapter 20
More about C++ ClassesCS-2303, C-Term 2010 3
Preprocessor Wrappers
• Prevent code from being included more than once.– #ifndef – “if not defined”
• Skip this code if it has been included already– #define
• Define a name so this code will not be included again– #endif
• If the header has been included previously– Name is defined already and the header file is not included again.
• Prevents multiple-definition errors• Example
– #ifndef TIME_H#define TIME_H… // code#endif
Exactly as in C
Figure 20.1 in D&D
More about C++ ClassesCS-2303, C-Term 2010 4
Example Class
class TreeNode {public:
... /* other methods */TreeNode(const string &newWord);//constructor~TreeNode(); //destructor
private:const string word;int count;TreeNode *left, *right;
};
Note: heavy use of const is typical
of good C++ programming style
In this design, once a word is assigned to a TreeNode, that word never changes.
More about C++ ClassesCS-2303, C-Term 2010 5
Example Class
class TreeNode {public:
... /* other methods */TreeNode(const string &newWord);//constructor~TreeNode(); //destructor
private:const string word;int count;TreeNode *left, *right;
};
What does the constructor methodof TreeNode have to do?
More about C++ ClassesCS-2303, C-Term 2010 6
What Must Constructor Do?
• (Allocate memory for object)• Done before constructor method is called
• Initialize left, right• To NULL
• Initialize count• To 1
• Create a string object word and initialize• How?
More about C++ ClassesCS-2303, C-Term 2010 7
Creating Member Objects
class TreeNode {
...
string word;
...
};
TreeNode::TreeNode (string &newWord) {
...
word = newWord;
...
};
A string object is a member ofTreeNode
Therefore, string constructoris automatically called to initialize object word before TreeNodeconstructor method is called
TreeNode constructor can thenbe programmed to set theinitial value of word to benewWord (the parameter)
More about C++ ClassesCS-2303, C-Term 2010 8
What About const Members?
class TreeNode {public:... /* other methods */TreeNode(const string &newWord);//constructor~TreeNode(); //destructor
private:const string word;int count;TreeNode *left, *right;
};
A const object may nev
er be
on left side of assignment
Not even in a constructor!
More about C++ ClassesCS-2303, C-Term 2010 9
Constructor with const Member
TreeNode::TreeNode(const string &newWord){left = right = NULL;count = 1;word = newWord;
}
class TreeNode {...
private:const string word;int count;TreeNode *left, *right;
};
Error detected by compiler.
More about C++ ClassesCS-2303, C-Term 2010 10
Solution – Initializer List
• A list of member-value pairs– Or member-constructor pairs
• Between the () of the constructor header and the {} of the constructor body– Preceded by ':' and separated by ','
More about C++ ClassesCS-2303, C-Term 2010 11
Example – Initializer List
TreeNode::TreeNode(const string &newWord):word(newWord), //initialize wordcount(1), //initialize countleft(NULL),right(NULL)
{
/* rest of constructor body */
} // TreeNode constructor
Invokes the string constructor
to create a new const string
object from the argument
Widely used in the design of C++ classes
More about C++ ClassesCS-2303, C-Term 2010 12
Common Programming Error 21.5
• Not providing a member initializer for a const data member is a compilation error.
More about C++ ClassesCS-2303, C-Term 2010 13
Common Programming Error 21.6
• A compilation error occurs if – a member object is not initialized with a
member initializer
• and – the member object’s class does not provide a
default constructor• Even if member object’s class defines one or more
constructors, but none is a default constructor.
More about C++ ClassesCS-2303, C-Term 2010 14
Questions?
More about C++ ClassesCS-2303, C-Term 2010 15
Destructors
• The opposite of constructors
• Called to clean up objects before deleting them– Very important if your class contains objects of
other classes inside of it.– E.g., string
• Dynamically allocates array of characters to hold the string itself
• Must be freed before string object can be deleted
More about C++ ClassesCS-2303, C-Term 2010 16
Example
class TreeNode {public:
... /* other methods */TreeNode(const string &newWord);//constructor~TreeNode();
//destructor
private:const string word;int count;TreeNode *left, *right;
};
TreeNode::~TreeNode() {if (left) {
delete left;left = NULL;
}
if (right) {delete right;right = NULL;
}}
Note: destructor for string word andfor count are called automatically(because these are in class scope).
Destructors for left and right have to be called forcibly, because thoseobject were allocated dynamically
More about C++ ClassesCS-2303, C-Term 2010 17
When are Constructors Called?
• Global Scope — I.e., objects declared outside of any function
– Before main() is called!• Function or Block Scope — I.e., automatic variables and
constants– When execution reaches point where object is declared– For static objects, the first time execution reaches
point where object is declared• Class Scope — I.e., data members of a class
– When class constructor executes initialization list (or enters block scope of constructor function)
• Dynamic objects — I.e., objects created by new– Constructor is invoked by new operator
Deitel & Deitel, §20.8
More about C++ ClassesCS-2303, C-Term 2010 18
When are Destructors Called?
• In opposite order of constructors (mostly)
• Dynamic objects• Invoked by delete operator
• Class scope — I.e., data members of a class
• Invoked by destructor of class object
• Function or Block Scope• When just before leaving the scope
• Global Scope• After main() has returned
More about C++ ClassesCS-2303, C-Term 2010 19
When are Destructors Called – Exceptions
• static objects in function or block scope• After main() has returned but before calling
destructors of objects in Global Scope
• exit() function• Destructors of automatic objects are not called• Usually means abnormal termination of program,
file cannot be opened, etc.
• abort() function• No destructors are called• Usually means serious error, etc.
Deitel & Deitel, §20.8
More about C++ ClassesCS-2303, C-Term 2010 20
Dynamically Allocated Objects
• Always use new operator (as in Java)• Returns pointer to object (as with malloc() in C)
• Never use malloc()• There is a lot more to creating an object in C++ than simply
allocating memory• new calls malloc() to allocate memory, calls constructor,
sets up inheritance, finds the right polymorphic functions, etc.
• Always use delete operator• Invokes destructor, cleans up, calls free(), etc.• Takes pointer to object
• Never call free() directly• For same reasons not to call malloc(); memory leaks, etc.
More about C++ ClassesCS-2303, C-Term 2010 21
Questions?
More about C++ ClassesCS-2303, C-Term 2010 22
Dynamically Allocated Arrays
• new can be used to dynamically allocate arrays
• Examples:–int *myArray = new int[10];double *dArray = new double[2*n+1];TreeNode *silly = new TreeNode[k];
• Calls default constructor for each element• No arguments for initializing individual elements!
Deitel & Deitel, §21.6
More about C++ ClassesCS-2303, C-Term 2010 23
Using Dynamically Allocated Arrays
• Examples:–int *myArray = new int[10];double *dArray = new double[2*n+1];TreeNode *silly = new TreeNode[k];
• Example usage:–myArray[0], ... myArray[9] dArray[i], dArray[j], ...int c = silly[k-1].getCount()
More about C++ ClassesCS-2303, C-Term 2010 24
Deleting Dynamically Allocated Arrays
delete[] myArray;delete[] dArray;delete[] silly;
• Calls the destructor for each element before deallocating memory!
• Note:– – delete myArray only calls destructor for first
element!
More about C++ ClassesCS-2303, C-Term 2010 25
Common Programming Error 21.9
• Using delete instead of delete[] can lead to runtime logic errors.
• To ensure that every element receives a destructor call, be sure to use delete[]
• To call the destructor for an individual element, use delete for that element only
• Why would anyone want to do this?
More about C++ ClassesCS-2303, C-Term 2010 26
Questions?
More about C++ ClassesCS-2303, C-Term 2010 27
Stream Manipulators
• setfill(), setw()• Sets fill character and field width of stream
• Examplescout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second << endl;
cout.setw(2); // sets all field widths
Deitel & Deitel, Fig 20.2
More about C++ ClassesCS-2303, C-Term 2010 28
More Stream Manipulators
• setprecision()• Sets precisions (in decimal places) of floating point
numbers
• eof()• Returns a bool indicating whether the end of the
stream has been reached
• True only after program attempts to read past last character of the stream
• Usage:– cin.eof()
More about C++ ClassesCS-2303, C-Term 2010 29
Other Useful Stream (Member) Functions
• getline()• Reads stream to next newline, returns string
• get()• Reads one character from input stream, returns int
• put()• Writes one character to output stream
• A long list of manipulators at• http://www.cplusplus.com/reference/iostream/
• Deitel & Deitel, Chapter 26
More about C++ ClassesCS-2303, C-Term 2010 30
Questions?