Title: CS-2303 System Programming Concepts
1More 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)
2Reading Assignment
- Deitel Deitel, 5th edition, Chapter 20
3Preprocessor 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_Hdefine TIME_H // codeendif
Exactly as in C
Figure 20.1 in DD
4Example 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.
5Example 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?
6What 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?
7Creating Member Objects
A string object is a member ofTreeNode Therefore,
string constructoris automatically called to
initialize object word before TreeNodeconstructo
r method is called
- class TreeNode
- ...
- string word
- ...
-
- TreeNodeTreeNode (string newWord)
- ...
- word newWord
- ...
TreeNode constructor can thenbe programmed to
set theinitial value of word to benewWord (the
parameter)
8What About const Members?
- class TreeNode
- public
- ... / other methods /
- TreeNode(const string newWord) //constructor
- TreeNode() //destructor
- private
- const string word
- int count
- TreeNode left, right
-
9Constructor with const Member
- TreeNodeTreeNode(const string newWord)left
right NULLcount 1 - word newWord
-
- class TreeNode
- ...
- private
- const string word
- int count
- TreeNode left, right
10Solution 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 ','
11Example Initializer List
- TreeNodeTreeNode(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
12Common Programming Error 21.5
- Not providing a member initializer for a const
data member is a compilation error.
13Common Programming Error 21.6
- A compilation error occurs if
- a member object is not initialized with a member
initializer - and
- the member objects class does not provide a
default constructor - Even if member objects class defines one or more
constructors, but none is a default constructor.
14Questions?
15Destructors
- 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
16Example
- class TreeNode
- public
- ... / other methods /
- TreeNode(const string newWord) //constructor
- TreeNode() //destructor
- private
- const string word
- int count
- TreeNode left, right
- TreeNodeTreeNode() if (left) delete
left left NULLif (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
17When are Constructors Called?
Deitel Deitel, 20.8
- 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
18When 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
19When 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
20Dynamically 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.
21Questions?
22Dynamically Allocated Arrays
Deitel Deitel, 21.6
- new can be used to dynamically allocate arrays
- Examples
- int myArray new int10double dArray new
double2n1TreeNode silly new TreeNodek - Calls default constructor for each element
- No arguments for initializing individual elements!
23Using Dynamically Allocated Arrays
- Examples
- int myArray new int10double dArray new
double2n1TreeNode silly new TreeNodek - Example usage
- myArray0, ... myArray9 dArrayi,
dArrayj, ...int c sillyk-1.getCount()
24Deleting Dynamically Allocated Arrays
- delete myArraydelete dArraydelete
silly - Calls the destructor for each element before
deallocating memory! - Note
- delete myArray only calls destructor for first
element!
25Common 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?
26Questions?
27Stream Manipulators
- setfill(), setw()
- Sets fill character and field width of stream
- Examples
- cout ltlt setfill('0') ltlt setw(2) ltlt hour ltlt "" ltlt
setw(2) ltlt minute ltlt "" ltlt setw(2) ltlt second ltlt
endl - cout.setw(2) // sets all field widths
Deitel Deitel, Fig 20.2
28More 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()
29Other 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
30Questions?
31Review Constructors
- Initialize an object of a class
- 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