C++ Language - Session 6: Class Basics (cont) - FPT University

ppt 41 trang hoanguyen 3040
Bạn đang xem 20 trang mẫu của tài liệu "C++ Language - Session 6: Class Basics (cont) - FPT University", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên

Tài liệu đính kèm:

  • pptc_language_session_6_class_basics_cont_fpt_university.ppt

Nội dung text: C++ Language - Session 6: Class Basics (cont) - FPT University

  1. Session 6 – Class Basics Contd Deep Copies Custom iostream Operators Conversion Operators Session 6 – Class Basics Contd 1/41
  2. Objectives • Deep Copies – Resources – Copy Constructor – Assignment Operator – Localization – No Copies Allowed • Custom iostream Operators – Cascading – Returning A Reference – Custom io Operators – String Class Session 6 – Class Basics Contd 2/41
  3. Objectives • Conversion Operators – Primitive Data Type Conversions – Derived Data Type Conversions – Design Considerations – Single-Argument Constructors – Overloaded Operators Session 6 – Class Basics Contd 3/41
  4. Deep Copies • Objects that include either instance variables or objects that refer to resources require the copying of resources themselves. Session 6 – Class Basics Contd 4/41
  5. Resources • Resources are stored outside the memory allocated to an object. • Instance variables that refer to resources (resource instance variables) include pointers to – dynamic arrays in freestore memory, and – file structures Session 6 – Class Basics Contd 5/41
  6. Resource instance variables Example Session 6 – Class Basics Contd 6/41
  7. Copying • If we were to make a shallow copy of a Student object, the original and the copy would point to the same resource: grade pointer • If any changes the grades in the copy, the original referred to the changed grades and no longer to the original grades. This behavior is not what we normally expect from a copy. Session 6 – Class Basics Contd 7/41
  8. Copying • For each resource variable, we obtain a pointer to a new resource and copy the original into that resource. • To enable deep copying, we overwrite the compiler defaults for two member functions: – the copy constructor and – the assignment operator If we do not define a copy constructor, the compiler inserts one that makes a shallow copy. If we do not define an assignment operator, the compiler inserts one that performs a shallow assignment. Session 6 – Class Basics Contd 8/41
  9. Copy Constructor • The copy constructor copies information from an existing object to a newly created object. • The compiler calls this constructor whenever an object is – initialized, – passed by value to a function parameter, or – returned by value from a function Session 6 – Class Basics Contd 9/41
  10. Copy Constructor • A copy constructor declaration: Identifier ( const Identifier& ); – Identifier is the class name. In the definition of the copy constructor, we • perform a shallow copy of the non-resource instance variables, • allocate fresh freestore memory for the resource instance variable(s), and • copy data pointed to by the original object to the freshly allocated memory pointed to by the new object. Session 6 – Class Basics Contd 10/41
  11. Copy Ctor demo Session 6 – Class Basics Contd 11/41
  12. Assignment Operator • An assignment operator copies data from an existing object into an existing object. Identifier& operator=(const Identifier&); (Identifier: is the name of the class of the right operand) In the definition, we: – check for self-assignment – deallocate previously allocated freestore memory – allocate new freestore memory – copy resource source data to freshly allocated memory – copy non-resource instance variables to destination variables Session 6 – Class Basics Contd 12/41
  13. Assignment Operator Demo Session 6 – Class Basics Contd 13/41
  14. No Copies Allowed • To prohibit the copying and the assigning of objects, we declare the copy constructor and the assignment operator as private members Session 6 – Class Basics Contd 14/41
  15. Review • Deep Copies – Resources – Copy Constructor – Assignment Operator – Localization – No Copies Allowed Session 6 – Class Basics Contd 15/41
  16. Custom iostream Operators • An object can interact with input and output streams in the same way that primitive data types interact. • The istream and ostream classes of the iostream library support object-oriented input and output. Session 6 – Class Basics Contd 16/41
  17. Custom iostream Operators • We extend the functionality of the extraction (>>) and the insertion (<<) operators to objects of our own design by overloading the operators to accept our objects as rights operands. Session 6 – Class Basics Contd 17/41
  18. Cascading • Cascading is the concatenation of several variables in a single statement interspersed with the appropriate operator. • The insertion and extraction operators are overloaded in the istream and ostream classes so as to enable cascading. Session 6 – Class Basics Contd 18/41
  19. Cascading • For example the compiler interprets: cout << x << y; as cout << x; //return cout cout << y; • We implement cascading by returning a reference to the left operand. Session 6 – Class Basics Contd 19/41
  20. Returning A Reference • Returning a reference from a function has two intrinsic benefits: – efficiency – creates an lvalue • Returning a reference copies a single address. (Returning the value at that address may involve copying many instance variables, possibly even deep copying, which is much more time consuming.) Session 6 – Class Basics Contd 20/41
  21. lvalue Creation • The term lvalue originates in the description of an assignment expression. • An assignment expression consists of a left operand, the assignment operator and a right operand. The left operand must occupy some memory location where the value of the right operand may be stored. The left operand cannot be a constant or a temporary expression. • Examples of lvalues include: – variables – objects – array elements – functions that return references Session 6 – Class Basics Contd 21/41
  22. Dangling References • Returning a reference to a local variable or a parameter received by value (these go out of scope when the function returns control to its caller) is called a dangling reference. Session 6 – Class Basics Contd 22/41
  23. Custom io Operators • To create custom I/O operators for a class, we overload the insertion and extraction operators as non-member helper functions. • The declarations: istream& operator>>(istream&, Identifier&); ostream& operator<<(ostream&, const Identifier&); Session 6 – Class Basics Contd 23/41
  24. Custom io Operators Session 6 – Class Basics Contd 24/41
  25. Custom io Operators Demo Session 6 – Class Basics Contd 25/41
  26. String Input overflow • The Problem – String input poses a unique problem. We cannot predict at compile time the maximum number of characters that a user will enter as a string. – If we wish to accept all of the characters that a user enters, we need a method of accepting input that avoids overflow. Session 6 – Class Basics Contd 26/41
  27. String Input overflow Demo Session 6 – Class Basics Contd 27/41
  28. String Input overflow • The Solution – The string class addresses this indefinite-size problem. An object of the string class accepts as many characters as the user enters and allocates as much memory as is needed to store the set of characters. – The string class requires #include for the prototypes. Session 6 – Class Basics Contd 28/41
  29. String Input overflow istream& getline(istream&, string&, char); • The string class has two member functions for translating strings into null-terminated C-style strings: – length() - the number of characters in the string – c_str() - the address of the null-terminated C-style version of the string. Session 6 – Class Basics Contd 29/41
  30. Input using String Class Demo Session 6 – Class Basics Contd 30/41
  31. Review • Custom iostream Operators – Cascading – Returning A Reference – Custom io Operators – String Class Session 6 – Class Basics Contd 31/41
  32. Conversion Operators • Occasionally, we need to convert an object of one class to an object of another data type. Conversion operators serve this purpose. Session 6 – Class Basics Contd 32/41
  33. Primitive Data Type Conversions • Conversion operators define implicit conversions to different Student::operator int() const{ data types, including primitive data types. return no; operator dataType() const; } Session 6 – Class Basics Contd 33/41
  34. Derived Data Type Conversions Session 6 – Class Basics Contd 34/41
  35. Design Considerations • Conversion operators should be used sparingly and their implementations kept trivial. • Too many conversion operators can easily lead to ambiguities. Session 6 – Class Basics Contd 35/41
  36. Single-Argument Constructors • Conversion operators define implicit conversions from the data type of the current object to another data type. • To define a conversion from a data type to the data type of the current object, we use single- argument constructors. Session 6 – Class Basics Contd 36/41
  37. Conversion Sequence • A compiler, when it encounters a function call (a call to an operator overloaded), performs an elaborate search before translating the call. • The rules for determining the best fit are complex and the results may sometimes be surprising. • The compiler first identifies all functions with the same name and the same number of parameters as the function call. Session 6 – Class Basics Contd 37/41
  38. Conversion Sequence • In searching for a conversion the compiler steps through definite stages. The compiler looks for – an exact match (for example, int to int, Student to Student), – a promoted match (for example, char to int, float to double), – a standard conversion match (for example, int to double, int to float), – a derived data type conversion match (for example, int to Student). Session 6 – Class Basics Contd 38/41
  39. Explicit Constructors • To suppress implicit conversions by a single- argument constructor, we qualify the constructor as explicit explicit ClassIdentifier(dataType); • For an explicit single-argument constructor, we need to write harry = Student(1234); instead of harry = 1234; Session 6 – Class Basics Contd 39/41
  40. Review • Conversion Operators – Primitive Data Type Conversions – Derived Data Type Conversions – Design Considerations – Single-Argument Constructors – Overloaded Operators Session 6 – Class Basics Contd 40/41
  41. Summary • Deep Copies – Resources – Copy Constructor – Assignment Operator – Localization – No Copies Allowed • Custom iostream Operators – Cascading – Returning A Reference Q&A – Custom io Operators – String Class • Conversion Operators – Primitive Data Type Conversions – Derived Data Type Conversions – Design Considerations – Single-Argument Constructors – Overloaded Operators Session 6 – Class Basics Contd 41/41