CS-2303 System Programming Concepts - PowerPoint PPT Presentation

About This Presentation
Title:

CS-2303 System Programming Concepts

Description:

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 ... – PowerPoint PPT presentation

Number of Views:49
Avg rating:3.0/5.0
Slides: 31
Provided by: Hug130
Learn more at: http://web.cs.wpi.edu
Category:

less

Transcript and Presenter's Notes

Title: CS-2303 System Programming Concepts


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)

2
Reading Assignment
  • Deitel Deitel, 5th edition, Chapter 20

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_Hdefine TIME_H // codeendif

Exactly as in C
Figure 20.1 in DD
4
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.
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?
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?

7
Creating 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)
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

9
Constructor with const Member
  • TreeNodeTreeNode(const string newWord)left
    right NULLcount 1
  • word newWord
  • class TreeNode
  • ...
  • private
  • const string word
  • int count
  • TreeNode left, right

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 ','

11
Example 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
12
Common Programming Error 21.5
  • Not providing a member initializer for a const
    data member is a compilation error.

13
Common 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.

14
Questions?
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

16
Example
  • 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
17
When 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

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

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
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.

21
Questions?
22
Dynamically 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!

23
Using 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()

24
Deleting 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!

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?

26
Questions?
27
Stream 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
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()

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

30
Questions?
31
Review 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
Write a Comment
User Comments (0)
About PowerShow.com