300 likes | 392 Views
More about C++ Classes. CS-2303 System Programming Concepts (Slides include materials from The C Programming Language , 2 nd edition, by Kernighan and Ritchie and from C: How to Program , 5 th and 6 th editions, by Deitel and Deitel). Reading Assignment.
E N D
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++ Classes
Reading Assignment • Deitel & Deitel, 5th edition, Chapter 20 More about C++ Classes
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++ Classes
Note: heavy use of const is typicalof good C++ programming style Example Class class TreeNode { public: ... /* other methods */ TreeNode(const string &newWord); //constructor ~TreeNode(); //destructor private: const string word; int count; TreeNode *left, *right; }; In this design, once a word is assigned to a TreeNode, that word never changes. More about C++ Classes
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++ Classes
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++ Classes
Creating Member Objects A string object is a member ofTreeNode Therefore, string constructoris automatically called to initialize object word before TreeNodeconstructor method is called class TreeNode { ... string word; ... }; TreeNode::TreeNode (string &newWord) { ... word = newWord; ... }; TreeNode constructor can thenbe programmed to set theinitial value of word to benewWord (the parameter) More about C++ Classes
A const object may never beon left side of assignment Not even in a constructor! 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; }; More about C++ Classes
Error detected by compiler. 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; }; More about C++ Classes
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++ Classes
Invokes the string constructorto create a new const stringobject from the argument 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 Widely used in the design of C++ classes More about C++ Classes
Common Programming Error 21.5 • Not providing a member initializer for a const data member is a compilation error. More about C++ Classes
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++ Classes
Questions? More about C++ Classes
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++ Classes
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;} } Example Note: destructor for stringword 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++ Classes
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 More about C++ Classes
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++ Classes
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++ Classes
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++ Classes
Questions? More about C++ Classes
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! More about C++ Classes
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++ Classes
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++ Classes
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++ Classes
Questions? More about C++ Classes
Stream Manipulators • 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 More about C++ Classes
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++ Classes
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++ Classes
Questions? More about C++ Classes