A Deeper Look at Classes

Similar documents
Computer Programming with C++ (21)

W8.1 Continuing Classes friend Functions and friend Classes Using the this Pointer Cascading Function Calls

1 // Fig. 6.13: time2.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> Outline. 4 5 using std::cout; 6 7 #include <iomanip>

Classes: A Deeper Look. Systems Programming

Computer Programming Class Members 9 th Lecture

Pointer Assignments. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 18 October 29, The new Operator

Classes: A Deeper Look

Chapter 6: Classes and Data Abstraction

Fig. 7.1 Fig. 7.2 Fig. 7.3 Fig. 7.4 Fig. 7.5 Fig. 7.6 Fig. 7.7 Fig. 7.8 Fig. 7.9 Fig. 7.10

Angela Chih-Wei Tang Visual Communications Lab Department of Communication Engineering National Central University JhongLi, Taiwan.

Chapter 9 Classes : A Deeper Look, Part 1

Chapter 17 - C++ Classes: Part II

OBJECT ORIENTED PROGRAMMING USING C++

Introduction to Programming session 24

57:017, Computers in Engineering C++ Classes

9.1 Introduction. Integrated Time class case study Preprocessor wrapper Three types of handles on an object. Class functions

IS 0020 Program Design and Software Tools

Classes: A Deeper Look, Part 2

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools

Chapter 16: Classes and Data Abstraction

More C++ Classes. Systems Programming

Preview 11/1/2017. Constant Objects and Member Functions. Constant Objects and Member Functions. Constant Objects and Member Functions

Classes and Data Abstraction. Topic 5

Fundamentals of Programming Session 24

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES II

Classes: A Deeper Look, Part 1

Classes, Constructors, etc., in C++

Chapter 7: Classes Part II

Deitel Dive-Into Series: Dive-Into Cygwin and GNU C++

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

OBJECT-ORIENTED PROGRAMMING CONCEPTS-CLASSES IV

l A class in C++ is similar to a structure. l A class contains members: - variables AND - public: accessible outside the class.

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! A class in C++ is similar to a structure. ! A class contains members: - variables AND. - public: accessible outside the class.

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

The Class. Classes and Objects. Example class: Time class declaration with functions defined inline. Using Time class in a driver.

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

Classes and Objects: A Deeper Look

this Pointer, Constant Functions, Static Data Members, and Static Member Functions this Pointer (11.1) Example of this pointer

clarity. In the first form, the access specifier public : is needed to {

Object Oriented Design

Classes and Data Abstraction

Preview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

Your first C and C++ programs

Classes and Data Abstraction. Topic 5

Object-Based Programming (Deitel chapter 8)

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Operator Overloading in C++ Systems Programming

Lecture 5. Function Pointers

CS 1337 Computer Science II Page 1

Exception Handling in C++

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. 1

Operator Overloading

Classes and Objects. Types and Classes. Example. Object Oriented Programming

Programming Assignment #4 Binary Trees in C++

Derived Classes in C++

Chapter 18 - C++ Operator Overloading

Constructor - example

Iterators. Professor Hugh C. Lauer CS-2303, System Programming Concepts

III. Classes (Chap. 3)

Linked Lists in C and C++

Containers and the Standard Template Library (STL)

Chapter 15 - C++ As A "Better C"

Object-Based Programming

W8.2 Operator Overloading

Encapsulation. Contents. Steven Zeil. July 17, Encapsulation Encapsulation in C Classes 4. 3 Hiding Attributes 8

Introduction to C++ Systems Programming

Fundamentals of Programming Session 25

Introduction. W8.2 Operator Overloading

C How to Program, 6/e, 7/e

2. It is possible for a structure variable to be a member of another structure variable.

Classes and Objects: A Deeper Look

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Introduction to C++ Introduction to C++ 1

Operator Overloading

An inline function is one in which the function code replaces the function call directly. Inline class member functions

Arrays. Week 4. Assylbek Jumagaliyev

Software Development With Java CSCI

Object Oriented Design

Review: C++ Basic Concepts. Dr. Yingwu Zhu

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Introduction Of Classes ( OOPS )

IS 0020 Program Design and Software Tools

Classes and Objects:A Deeper Look

Pointers and Strings Prentice Hall, Inc. All rights reserved.

SFU CMPT Topic: Classes

Pointers and Strings. Adhi Harmoko S, M.Komp

Operator Overloading

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Intermediate Programming, Spring 2017*

Introduction & Review

G205 Fundamentals of Computer Engineering. CLASS 3, Wed. Sept Stefano Basagni Fall 2004 M-W, 1:30pm-3:10pm

Dynamic Memory Allocation (and Multi-Dimensional Arrays)

Transcription:

A Deeper Look at Classes Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel) 1

const Objects & const Member Functions Principle of Least Privilege Allow access to data only when absolutely needed Fundamental principle of good software engineering const objects Keyword const Specifies that an object is not modifiable Attempts to modify const object compilation errors Example const Time noon (12, 0, 0); 2

const Member Functions Only const member functions can be called for const objects Member functions declared const may not modify the object in any way A function is specified as const both prototype and definition. Constructors and destructors are not const By definition! 3

const Example 1 // Fig. 21.1: Time.h 2 // Definition of class Time. 3 // Member functions defined in Time.cpp. 4 #ifndef TIME_H 5 #define TIME_H 6 7 class Time 8 { 9 public: 10 Time( int = 0, int = 0, int = 0 ); // default constructor 11 12 // set functions 13 void settime( int, int, int ); // set time 14 void sethour( int ); // set hour 15 void setminute( int ); // set minute 16 void setsecond( int ); // set second 17 18 // get functions (normally declared const) 19 int gethour() const; // return hour 20 int getminute() const; // return minute 21 int getsecond() const; // return second A promise that these functions do not modify the object at all 4

const Example (continued) 22 23 // print functions (normally declared const) 24 void printuniversal() const; // print universal time 25 void printstandard(); // print standard time (should be const) 26 private: 27 int hour; // 0-23 (24-hour clock format) 28 int minute; // 0-59 29 int second; // 0-59 30 }; // end class Time 31 32 #endif 5

const Example (continued) 1 // Fig. 21.2: Time.cpp 2 // Member-function definitions for class Time. 3 #include <iostream> 4 using std::cout; 5 6 #include <iomanip> 7 using std::setfill; 8 using std::setw; 9 10 #include "Time.h" // include definition of class Time 11 12 // constructor function to initialize private data; 13 // calls member function settime to set variables; 14 // default values are 0 (see class definition) 15 Time::Time( int hour, int minute, int second ) 16 { 17 settime( hour, minute, second ); 18 } // end Time constructor 19 20 // set hour, minute and second values 21 void Time::setTime( int hour, int minute, int second ) 22 { 23 sethour( hour ); 24 setminute( minute ); 25 setsecond( second ); 26 } // end function settime 6

const Example (continued) 27 28 // set hour value 29 void Time::setHour( int h ) 30 { 31 hour = ( h >= 0 && h < 24 )? h : 0; // validate hour 32 } // end function sethour 33 34 // set minute value 35 void Time::setMinute( int m ) 36 { 37 minute = ( m >= 0 && m < 60 )? m : 0; // validate minute 38 } // end function setminute 39 40 // set second value 41 void Time::setSecond( int s ) 42 { 43 second = ( s >= 0 && s < 60 )? s : 0; // validate second 44 } // end function setsecond 45 46 // return hour value 47 int Time::getHour() const // get functions should be const 48 { 49 return hour; 50 } // end function gethour const keyword in function definition, as well as in function prototype 7

const Example (continued) 51 52 // return minute value 53 int Time::getMinute() const 54 { 55 return minute; 56 } // end function getminute 57 58 // return second value 59 int Time::getSecond() const 60 { 61 return second; 62 } // end function getsecond 63 64 // print Time in universal-time format (HH:MM:SS) 65 void Time::printUniversal() const 66 { 67 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 68 << setw( 2 ) << minute << ":" << setw( 2 ) << second; 69 } // end function printuniversal 70 71 // print Time in standard-time format (HH:MM:SS AM or PM) 72 void Time::printStandard() // note lack of const declaration 73 { 74 cout << ( ( hour == 0 hour == 12 )? 12 : hour % 12 ) 75 << ":" << setfill( '0' ) << setw( 2 ) << minute 76 << ":" << setw( 2 ) << second << ( hour < 12? " AM" : " PM" ); 77 } // end function printstandard 8

Purpose of const To enlist the aid of the compiler in detecting unwanted changes to objects Widely used in large programming projects Helps maintain sanity, teamwork, etc. Get used to using const everywhere! For methods, parameters, etc. 9

Questions? 10

Default Memberwise Assignment Absolute C++, 8.3 Assignment operator (=) Can be used to assign an object to another object of the same type. Each data member of the right object is assigned to the same data member in the left object. Not usually want you want to do! Usually causes serious problems when data members contain pointers to dynamically allocated memory!! Because pointers are simply copied 11

Default Memberwise Assignment Example 1 // Fig. 20.17: Date.h 2 // Declaration of class Date. 3 // Member functions are defined in Date.cpp 4 5 // prevent multiple inclusions of header file 6 #ifndef DATE_H 7 #define DATE_H 8 9 // class Date definition 10 class Date 11 { 12 public: 13 Date( int = 1, int = 1, int = 2000 ); // default constructor 14 void print(); 15 private: 16 int month; 17 int day; 18 int year; 19 }; // end class Date 20 21 #endif Default initialization of data members 12

Default Memberwise Assignment (continued) 1 // Fig. 20.19: fig20_19.cpp 2 // Demonstrating that class objects can be assigned 3 // to each other using default memberwise assignment. 4 #include <iostream> 5 using std::cout; 6 using std::endl; 7 8 #include "Date.h" // include definition of class Date from Date.h 9 10 int main() 11 { 12 Date date1( 7, 4, 2004 ); 13 Date date2; // date2 defaults to 1/1/2000 14 15 cout << "date1 = "; 16 date1.print(); 17 cout << "\ndate2 = "; 18 date2.print(); 19 20 date2 = date1; // default memberwise assignment 21 22 cout << "\n\nafter default memberwise assignment, date2 = "; 23 date2.print(); 24 cout << endl; 25 return 0; 26 } // end main date1 = 7/4/2004 date2 = 1/1/2000 After default memberwise assignment, date2 = 7/4/2004 memberwise assignment assigns data members of date1 to date2 date2 now stores the same date as date1 14

But What happens if we use the default assignment operator on TreeNode? class TreeNode { public:... private: const string word; int count; TreeNode *left, *right; }; // class TreeNode 15

Default Memberwise Assignment (concluded) Many classes must provide their own assignment operator To intelligently assign one object to another Need to overload the = operator 16

Questions? 17

Copy Constructor Definition A constructor that has a single parameter of the form ClassName(ClassName &objecttobecopied); Normally A constructor that has a single constant parameter of the form ClassName(const ClassName &objecttobecopied); 18

Purpose of Copy Constructor To make a new object just like the previous object i.e., to make a copy of the previous object Intelligently E.g., string S1("Now is the time "); S1 contains an internal array of char string S2(S1); S2 now contains its own, separate internal array of char 19

Copy Constructors are used widely in programs are used implicitly by compiler whenever objects are passed by value! Passing objects to parameters Returning results from functions Initializing uninitialized memory from previous values 20

Copy Constructor A constructor that copies another object of the same type e.g.: class TreeNode { public:... /* other methods */ TreeNode(const TreeNode &nodetobecopied); // Copy Constructor private: const string word; int count; TreeNode *left, *right; }; 21

Default Copy Constructor Compiler provides a default copy constructor Copies each member of original object into corresponding member of new object i.e., memberwise assignment Enables pass-by-value for objects Used to copy original object s values into new object to be passed to a function or returned from a function Not usually want you want to do! Often causes serious problems when data members contain pointers to dynamically allocated memory!! Just like default memberwise assignment 22

Copy Constructor Many classes must provide an explicit Copy Constructor To intelligently copy one object to another Example: string(const string &stringtobecopied); Allocates new memory for the new string Copies characters from one to other Does not blindly copy members (including internal pointers, etc.) 23

Usage of Copy Constructor In Initializer list E.g.: TreeNode::TreeNode(const string &newword) :word(newword), //initialize word count(1), //initialize count left(null), right(null) { /* rest of constructor body */ } // TreeNode constructor 24

Questions? 25

The this Pointer Member functions know which object s data members to manipulate Every object has access to own address through a pointer called this (a C++ keyword) Object s this pointer is not part of object itself this pointer is passed (by the compiler) as an implicit argument to each of object s non-static member functions CS-2303, A-Term 2010 A Deeper Look at Classes 26

Using the this Pointer Objects may use the this pointer implicitly or explicitly this is used implicitly when accessing members directly It is used explicitly when using keyword this Type of the this pointer depends on type of the object whether member function is declared const CS-2303, A-Term 2010 A Deeper Look at Classes 27

Example using this 1 // Fig. 21.17: fig21_17.cpp 2 // Using the this pointer to refer to object members. 3 #include <iostream> 4 using std::cout; 5 using std::endl; 6 7 class Test 8 { 9 public: 10 Test( int = 0 ); // default constructor 11 void print() const; 12 private: 13 int x; 14 }; // end class Test 15 16 // constructor 17 Test::Test( int value ) 18 : x( value ) // initialize x to value 19 { 20 // empty body 21 } // end constructor Test CS-2303, A-Term 2010 A Deeper Look at Classes 28

Example using this (continued) 22 23 // print x using implicit and explicit this pointers; 24 // the parentheses around *this are required 25 void Test::print() const 26 { 27 // implicitly use the this pointer to access the member x 28 cout << " x = " << x; 29 30 // explicitly use the this pointer and the arrow operator 31 // to access the member x 32 cout << "\n this->x = " << this->x; 33 34 // explicitly use the dereferenced this pointer and 35 // the dot operator to access the member x 36 cout << "\n(*this).x = " << ( *this ).x << endl; 37 } // end function print 38 39 int main() 40 { 41 Test testobject( 12 ); // instantiate and initialize testobject 42 43 testobject.print(); 44 return 0; 45 } // end main x = 12 this->x = 12 (*this).x = 12 Directly accessing member x Explicitly using the this pointer to access member x Using the dereferenced this pointer and the dot operator CS-2303, A-Term 2010 A Deeper Look at Classes 29

Another Example Using this class ExtendTreeNode { public:... /* other methods */ ExtendTreeNode(const string &newword, ExtendTreeNode *parent); //constructor private: const string word; int count; ExtendTreeNode *left, *right ExtendTreeNode *const myparent; }; CS-2303, A-Term 2010 A Deeper Look at Classes 30

Example Using this (continued) ExtendTreeNode::ExtendTreeNode(const string &newword, ExtendTreeNode *parent) :word(newword), //initialize word count(1), //initialize count left(null), right(null), myparent(parent) //point back to myparent { /* rest of constructor body */ } // ExtendTreeNode constructor CS-2303, A-Term 2010 A Deeper Look at Classes 31

Example Using this (continued) ExtendTreeNode *ExtendTreeNode::AddNode(const string &newword){ if (newword == word){ count++; return this; } else if (newword < word) { if (left) return left->addnode(newword); else return left = new ExtendTreeNode(newWord, this); } else { /* same for right */ } } // AddNode Constructor of ExtendTreeNode with pointer back to parent node! CS-2303, A-Term 2010 A Deeper Look at Classes 32

Cascaded member-function calls Multiple functions are invoked in the same statement. Enabled by member functions returning the dereferenced this pointer. Example t.setminute( 30 ).setsecond( 22 ); Calls t.setminute( 30 ) and returns reference to t Then calls t.setsecond( 22 ); CS-2303, A-Term 2010 A Deeper Look at Classes 33

Cascaded calls (continued) Absolute C++, 8.3 (end) Instead of void setminute (const int ); Use Time& setminute (const int ); Implementation Time& Time::setMinute (const int m){ minute = m; return *this; } CS-2303, A-Term 2010 A Deeper Look at Classes 34

Reference Result A function may return a reference to an object (instead of a value) Value copy of an object Reference object itself Reference result must not be automatic variable Compiler checks Reference result may be used wherever an object of same type/class may be used Subject to const rules Especially useful for overloaded operators CS-2303, A-Term 2010 A Deeper Look at Classes 35

Questions? CS-2303, A-Term 2010 A Deeper Look at Classes 36