Chapter 13. 2 Objectives You should be able to describe: Assignment Pointers as Class Members Additional Class Features Common Programming Errors.

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Class and Objects.
Operator Overloading in C++ Systems Programming. Systems Programming: Operator Overloading 22   Fundamentals of Operator Overloading   Restrictions.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Classes: A Deeper Look Systems Programming.
2 Objectives You should be able to describe: Operator Functions Two Useful Alternatives – operator() and operator[] Data Type Conversions Class Inheritance.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
More C++ Classes Systems Programming. Systems Programming: C++ Classes 2 Systems Programming: 2 C++ Classes  Preprocessor Wrapper  Time Class Case Study.
Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.
CS-2303 System Programming Concepts
Operator OverloadingCS-2303, C-Term Operator Overloading CS-2303 System Programming Concepts (Slides include materials from The C Programming Language,
Operator Overloading in C++
Review of C++ Programming Part II Sheng-Fang Huang.
1 Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Using Classes Object-Oriented Programming Using C++ Second Edition 5.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 12: Adding Functionality to Your Classes.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
You gotta be cool. Access Functions and Utility Functions Preprocessor Wrapper Looking Ahead to Composition and Inheritance Object Size Class Scope and.
Pointer Data Type and Pointer Variables
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
More C++ Classes Systems Programming. C++ Classes  Preprocessor Wrapper  Time Class Case Study –Two versions (old and new)  Class Scope and Assessing.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
計算機程式語言 Lecture 13-1 國立臺灣大學生物機電系 13 Structures.
Learners Support Publications Classes and Objects.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Chapter 10 Introduction to Classes
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 11: Introduction to Classes. In this chapter you will learn about: – Classes – Basic class functions – Adding class functions – A case study involving.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Visual C# 2012 for Programmers © by Pearson Education, Inc. All Rights Reserved.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
Chapter 9 Classes: A Deeper Look, Part I Part II.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Overloading operators C++ incorporates the option to use standard operators to perform operations with.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Array in C++ / review. An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
Lecture 4 – Function (Part 1) FTMK, UTeM – Sem /2014.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Chapter 9 Classes: A Deeper Look, Part 1 Seventh Edition C++ How to Program © by Pearson Education, Inc. All Rights Reserved.
A First Book of C++ Chapter 12 Extending Your Classes.
Pointers and Dynamic Arrays
Chapter 7: User-Defined Functions II
About the Presentations
Chapter 9 Classes: A Deeper Look, Part 1
Classes and Objects.
9-10 Classes: A Deeper Look.
Recitation Course 0520 Speaker: Liu Yu-Jiun.
A Deeper Look at Classes
More C++ Classes Systems Programming.
9-10 Classes: A Deeper Look.
Presentation transcript:

Chapter 13

2 Objectives You should be able to describe: Assignment Pointers as Class Members Additional Class Features Common Programming Errors

3 Assignment Memberwise assignment: Allows assignment of data member values of an object to their counterparts in another object of the class –Compiler builds this type of default assignment if there are no instructions to the contrary Assignment operators: –Declared in class declaration section –Defined in class implementation section –Example: a = b; in main() of Program 13.1

4 Assignment (continued) #include using namespace std; // class declaration class Date { private: int month; int day; int year; public: Date(int = 7, int = 4, int = 2006); // constructor prototype void showDate(); // member function to display a Date };

5 Assignment (continued) // implementation section Date::Date(int mm, int dd, int yyyy) { month = mm; day = dd; year = yyyy; } void Date::showDate() { cout << setfill ('0') << setw(2) << month << '/' << setw(2) << day << '/' << setw(2) << year % 100; return; }

6 Assignment (continued) int main() { Date a(4,1,1999), b(12,18,2006); // declare two objects cout << "\nThe date stored in a is originally "; a.showDate(); // display the original date a = b; // assign b's value to a cout << "\nAfter assignment the date stored in a is "; a.showDate(); // display a's values cout << endl; return 0; }

7 Assignment (continued) Assignment operator declaration: –Format: void operator=(Date& ); Declares simple assignment operator for Date class of Program 13.1 Add to public section of class declarations –Keyword void : Assignment returns no value –operator= indicates overloading of assignment operator with new version –(className& ) : Argument to operator is class reference

8 Assignment (continued) Assignment operator implementation format: void Date::operator=(Date& newdate) { day = newdate.day; // assign the day month = newdate.month; // assign the month year = newdate.year; // assign the year } Add to implementation section of Program 13.1 –newdate : a reference to the Date class Reference parameters facilitate overloaded operators –day, month, and year members of newdate : Assigned to corresponding members of current object

9 Assignment (continued) Program 13.2: Program declaration and implementation of overloaded assignment operator ( operator=) Allows for assignments such as: a.operator= (b); –Calls overloaded assignment operator to assign b ’s members to a a.operator= (b) can be replaced with a = b;

10 Assignment (continued) Other issues affecting assignment operators –Use constant reference parameter Format: void Date::operator=(const Date& secdate); Precludes inadvertent change to secdtate –Assignment returns no value Cannot be used in multiple assignments such as: a = b = c Reason: a = b = c equivalent to a = (b + c) –But (b + c) returns no value making assignment to a an error

11 Copy Constructors Copy constructor: Initializes an object using another object of same class –Example: Two equivalent formats Date b = a; Date b(a); Default copy constructor: Constructed by compiler if none declared by programmer –Similar to default assignment constructor –Performs memberwise copy between objects –Does not work well with pointer data members

12 Copy Constructors (continued) Format: className(const className&); –Function name must be class name –Parameter is reference to class –Parameter specified as const to prevent inadvertent change Declaration: Copy constructor for Date class Date(const Date&);

13 Copy Constructors (continued) Implementation: Copy constructor for Date class Date::Date(const Date& olddate) { month = olddate.month; day = olddate.day; year = olddate.year; }

14 Base/Member Initialization Copy constructor does not perform true initialization –Creates and then assigns Base/Member initialization list: Initializes an object with no assignment –List can be applied only to constructor functions

15 Base/Member Initialization (continued) Base/Member initialization list construction: Two methods –Construct list in class declaration section: public: Date(int mo = 7, int da = 4, int yr = 2006): month(mo), day(da), year (yr) { }

16 Base/Member Initialization (continued) Base/Member initialization list construction: Two methods (continued) –Declare prototype in declaration section, and create list in implementation section // class declaration section public: Date(int = 7, int = 4, int = 2006); // prototype // class implementation section Date::Date(int mo, int da, int yr) : month(mo), day(da),year(yr) {}

17 Pointers as Class Members Program 13.4: Example of pointers: Declaration #include using namespace std; // class declaration class Test { private: int idNum; double *ptPay; public: Test(int = 0, double * = NULL); // constructor void setvals(int, double *); // access function void display(); // access function };

18 Pointers as Class Members (continued) Program 13.4: Example of pointers: Implementation Test::Test(int id, double *pt) { idNum = id; ptPay = pt; } void Test::setvals(int a, double *b) { idNum = a; ptPay = b; } void Test::display() { cout << "\nEmployee number " << idNum << " was paid $" << setiosflags(ios::fixed) << setiosflags(ios::showpoint) << setw(6) << setprecision(2) << *ptPay << endl; }

19 Pointers as Class Members (continued) Program 13.4: Example of pointers: main() int main() { Test emp; double pay = ; emp.setvals(12345, &pay); emp.display(); return 0; } Program 13.4 output: Employee number was paid $456.20

20 Pointers as Class Members (continued) Program 13.4 actions performed: –Test() constructor initializes: idNum data member to first parameter: 0 ptPay pointer member to second parameter: NULL –display() function: Outputs value pointed to by pointer member, ptPay Pointer member used like any other pointer variable –setvals() function: Alters member values after object is declared First parameter (an integer) is assigned to idNum Second parameter (an address) is assigned to ptPay

21 Pointers as Class Members (continued) Program 13.4 actions performed (continued): –main() function: Creates emp object emp initialized using constructor’s default arguments –setvals() function: assigns value and address of variable pay to emp object data members –display() function: Displays value whose address stored in emp.ptPay

22 Pointers as Class Members (continued)

23 Pointers as Class Members (continued) Example of pointer use: Store list of book titles –Inefficient to use fixed-length array –Use pointer member to character array Allocate array of correct size for each book title as needed –This arrangement illustrated in Figure13.3

24 Pointers as Class Members (continued)

25 Pointers as Class Members (continued) Class declaration for Program 13.5: List of book titles –Titles accessed as illustrated in Figure 13.3 #include using namespace std; class Book { private: char *title; // a pointer to a book title public: Book(char * = '\0'); // constructor void showtitle(void); // display the title };

26 Pointers as Class Members (continued) Implementation section for Program 13.5 –Defines Book() and showtitle() functions // class implementation Book::Book(char *strng) { title = new char[strlen(strng)+1]; // allocate memory strcpy(title,name); // store the string } void Book::showtitle(void) { cout << title << endl; }

27 Pointers as Class Members (continued) main() function of Program 13.5 int main() { Book book1("Windows Primer"); // create 1st title // 2nd title Book book2("A Brief History of Western Civilization"); book1.showtitle(); // display book1's title book2.showtitle(); // display book2's title return 0; }

28 Pointers as Class Members (continued)

29 Assignment Operators and Copy Constructors Reconsidered If a class contains no pointer data members, compiler-provided defaults work well for assignment operators and copy constructors –Compiler defaults provide member-by-member operation with no adverse side effects –Problems occur with defaults if pointers involved Example of problem: –Figure 13.5a shows pointers and allocated memory of Program 13.5 before execution

30 Assignment Operators and Copy Constructors Reconsidered (continued)

31 Assignment Operators and Copy Constructors Reconsidered (continued) Example of problem (continued): –Now insert statement: book 2 = book1; before closing brace of main() Compiler default assignment is used Produces memberwise copy –Address in book1 ’s pointer copied into book2 ’s pointer –Both pointers now point to same address –Address of A Brief History of Western Civilization is lost (as shown in figure 13.5b)

32 Assignment Operators and Copy Constructors Reconsidered (continued)

33 Assignment Operators and Copy Constructors Reconsidered (continued) Example of problem (continued): –Effect of loss of address of: A Brief History of Western Civilization No way for operating system to release this memory (until program terminates) If destructor attempts to release memory pointed to by book2, book1 will point to an undefined memory location Solution to problem: Copy book titles and leave pointers alone (as in figure 13.5c) – Must write our own assignment operator

34 Assignment Operators and Copy Constructors Reconsidered (continued)

35 Assignment Operators and Copy Constructors Reconsidered (continued) Definition of assignment operator void Book::operator=(Book& oldbook) { if(oldbook.title != NULL) // check that it exists delete(title); // release existing memory title = new char[strlen(oldbook.title) + 1]; // allocate new memory strcpy(title, oldbook.title); // copy the title } Problems associated with assignment operator also exist with default copy constructor –Need to also define a new copy constructor

36 Class Scope Names of data and function members are local to scope of class If global variable name reused within class, global variable is hidden by class data member Member function names are local to class they are declared in Local function variables hide names of class data members that have same name

37 Static Members As each class created, it gets its own block of memory for data members For every instantiation, we may want to share same memory location for specific variable –Example: In class of employee records each employee subject to same state sales tax Could make sales tax a global variable but this violates principles of data hiding Better option: Declare tax as a static class variable –Static data members act as global class variables

38 The this Pointer Each time an object is created, distinct area of memory is set aside for its data members No replication of memory for member functions –For each class, only one copy of member function is retained in memory –Each object uses same functions

39 The this Pointer (continued) Sharing member functions: Requires identification of data structure to be operated on –Accomplished by providing address information to function indicating location of object’s data structure –Example: statement a.showDate() passes address of object a into showDate() member function Question: Where is address of object a stored and how is it passed to showDate() this : Special pointer variable –Automatically supplied as hidden argument to each nonstatic member function that is called

40 Friend Functions Accessing and manipulating class’s private data members: Done only through member functions Sometime necessary to provide such access to nonmember functions Friend functions: List of nonmember functions that are granted same privileges as members Friends list: Series of function prototypes preceded by word friend and included in class’s declaration section –Example: friend double addreal(complex&, complex&);

41 Common Programming Errors Using default copy constructors and default assignment operators with classes that contain pointer values Using user-defined assignment operator in multiple assignment expression when operator has not been defined to return an object Using keyword static when defining either a static data or function member

42 Common Programming Errors (continued) Using keyword friend when defining a friend function –friend keyword should be used only within class declaration section Failing to instantiate static data members before creating class objects that must access these data members Forgetting that this is pointer that must be dereferenced using either *this or this->

43 Summary Assignment operator: May be declared with the function prototype: void operator=(className& ); Copy constructor: One object is initialized using another object of the same class: className(const className& ); Pointers: May be included as class members –Adhere to same rules as pointer variables

44 Summary (continued) Copy default constructors and default assignment operators typically not useful with classes that contain pointer members Class scope: Data and function members are local to scope of their class For each class object, separate set of memory locations is reserved for all data members except those declared as static

45 Summary (continued) Static function members apply to class as whole, rather than individual objects –Static function members can only access static data members and other static function members this : pointer argument used to pass address of an object’s data member to member functions friend : Class declaration that allows nonmember function to access class private data members