Download presentation
1
CS-2303 System Programming Concepts
More about C++ Classes CS-2303 System 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) CS-2303, C-Term 2010 More about C++ Classes
2
Reading Assignment Deitel & Deitel, 5th edition, Chapter 20
CS-2303, C-Term 2010 More about C++ Classes
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 CS-2303, C-Term 2010 More about C++ Classes
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. CS-2303, C-Term 2010 More about C++ Classes
5
Example Class What does the constructor method of TreeNode have to do?
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 method of TreeNode have to do? CS-2303, C-Term 2010 More about C++ Classes
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? CS-2303, C-Term 2010 More about C++ Classes
7
Creating Member Objects
A string object is a member of TreeNode Therefore, string constructor is automatically called to initialize object word before TreeNode constructor method is called class TreeNode { ... string word; }; TreeNode::TreeNode (string &newWord) { word = newWord; TreeNode constructor can then be programmed to set the initial value of word to be newWord (the parameter) CS-2303, C-Term 2010 More about C++ Classes
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 never be on left side of assignment Not even in a constructor! CS-2303, C-Term 2010 More about C++ Classes
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. CS-2303, C-Term 2010 More about C++ Classes
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 ',' CS-2303, C-Term 2010 More about C++ Classes
11
Example – Initializer List
TreeNode::TreeNode(const string &newWord) :word(newWord), //initialize word count(1), //initialize count left(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 CS-2303, C-Term 2010 More about C++ Classes
12
Common Programming Error 21.5
Not providing a member initializer for a const data member is a compilation error. CS-2303, C-Term 2010 More about C++ Classes
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. CS-2303, C-Term 2010 More about C++ Classes
14
Questions? CS-2303, C-Term 2010 More about C++ Classes
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 CS-2303, C-Term 2010 More about C++ Classes
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 and for count are called automatically (because these are in class scope). Destructors for left and right have to be called forcibly, because those object were allocated dynamically CS-2303, C-Term 2010 More about C++ Classes
17
When are Constructors Called?
Deitel & Deitel, §20.8 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 CS-2303, C-Term 2010 More about C++ Classes
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 CS-2303, C-Term 2010 More about C++ Classes
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 CS-2303, C-Term 2010 More about C++ Classes
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. CS-2303, C-Term 2010 More about C++ Classes
21
Questions? CS-2303, C-Term 2010 More about C++ Classes
22
Dynamically Allocated Arrays
Deitel & Deitel, §21.6 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! CS-2303, C-Term 2010 More about C++ Classes
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() CS-2303, C-Term 2010 More about C++ Classes
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! CS-2303, C-Term 2010 More about C++ Classes
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? CS-2303, C-Term 2010 More about C++ Classes
26
Questions? CS-2303, C-Term 2010 More about C++ Classes
27
Stream Manipulators Examples setfill(), setw()
Sets fill character and field width of stream Examples cout << setfill('0') << setw(2) << hour << ":" << setw(2) << minute << ":" << setw(2) << second << endl; cout.setw(2); // sets all field widths Deitel & Deitel, Fig 20.2 CS-2303, C-Term 2010 More about C++ Classes
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() CS-2303, C-Term 2010 More about C++ Classes
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 Deitel & Deitel, Chapter 26 CS-2303, C-Term 2010 More about C++ Classes
30
Questions? CS-2303, C-Term 2010 More about C++ Classes
31
Review – Constructors Initialize an object of a class Initializer List
I.e., set all data members to their initial values Especially members of other classes that need initialization Initializer List List of member-value pairs for setting values Follows header of constructor method, precedes body of constructor method Strongly recommended for good C++ programming style CS-2303, C-Term 2010 More about C++ Classes
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.