1 / 86

Class Functions and Conversions

11. Class Functions and Conversions. Contents. Assignment Additional class features Operator functions Data type conversions Random numbers and simulations Class inheritance Polymorphism Common programming errors. Assignment.

luka
Download Presentation

Class Functions and Conversions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 11 Class Functions and Conversions

  2. Contents • Assignment • Additional class features • Operator functions • Data type conversions • Random numbers and simulations • Class inheritance • Polymorphism • 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 Program 11.1: Assignment Example: Declaration #include <iostream> #include <iomanip> using namespace std; // class declaration class Date { private: int month; int day; int year; public: Date(int = 7, int = 4, int = 2005); // constructor prototype void showDate(); // member function to display a Date };

  5. Assignment Program 11.1: Assignment Example: Implementation // implementation section Date::Date(int mm, intdd, intyyyy) { 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 Program 11.1: Assignment Example: main() 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 • Assignment operator declaration: • Format:void operator=(Date& ); • Declares simple assignment operator for Date class of Program 11.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 • 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 11.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 • Program 11.2: Program 11.1 + 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 • Other issues affecting assignment operators • Use constant reference parameter • Format: void Date::operator=(const Date& secdate); • Precludes inadvertent change to secdate • 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 • 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 • Implementation: Copy constructor for Date class Date::Date(const Date& olddate) { month = olddate.month; day = olddate.day; year = olddate.year; }

  14. Copy Constructors c = a; Date c = a; Assignment Initialization Type definition Figure 11.1: Initialization and assignment

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

  16. Base/Member Initialization • 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) { }

  17. Base/Member Initialization • 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 with defaults // class implementation section Date::Date(int mo, int da, int yr) : month(mo), day(da),year(yr) {}

  18. Additional Class Features • Additional features include: • Class scope • Static class members • Granting access privileges to nonmember functions

  19. Class Scope • The scope of a variable defines the portion of a program where the variable can be assessed • Local variable scope is defined by any block inside a brace pair, {} • Each class defines an associated class scope • Names of data and function members are local to the scope of their class

  20. Class Scope • Global variables can be assessed from their point of declaration throughout the remaining portion of the file containing them with three exceptions • If a local variable has the same name, the global variable must be referenced with the scope resolution operator :: • A global variable’s scope can be extended into another file via the extern keyword • Same global name can be used in another file to define a separate variable via static keyword

  21. Class Scope • If global variable name is reused in a class, the global variable is hidden by the class member • Local variables hide the names of class data members having the same name • Member function names can only be used by objects declared for the class

  22. Class Scope • Example: scope of variables and functions double rate; // global // class declaration class Test { private: double amount, price, total; // class scope public: double extend(double, double); // class scope }

  23. Global(file)scope Classscope Local(block)scope double Test::extend(double amt, double pr) { amount = amt; price = pr; total = rate * amount * price; } Classscope Classscope Global(file)scope Class Scope Figure 11.2 Example of scopes

  24. Static Class Members • As each class object is created, it gets its own block of memory for its data members • In some cases, it is convenient for every instantiation of a class to share the same memory location for a specific variable

  25. Static Class Members Figure 11.3 Sharing the static data member taxRate

  26. Friend Functions • Private variables can be accessed and manipulated through a class’s member functions Figure 11.4a Direct access provided to member functions

  27. Friend Functions • External access to private functions can be granted through the friends list mechanism • The friends list members are granted the same privileges as a class’s member functions • Nonmember functions in the list are called friend functions • Friends list: Series of function prototype declarations preceded with the friend keyword

  28. Friend Functions • Program 11.6 • #include <iostream> • #include <cmath> • using namespace std; • // class declaration • class Complex • { • // friends list • friend double addreal(Complex&, Complex&); • friend double addimag(Complex&, Complex&); • private: • double real; • double imag; • public: • Complex(double = 0, double = 0); // constructor • void display(); • };

  29. Friend Functions • Program 11.6 (Continued) • // implementation section • Complex::Complex(double rl, double im) • { • real = rl; • imag = im; • } • void Complex::display() • { • char sign = '+'; • if(imag < 0) sign = '-'; • cout << real << sign << abs(imag) << 'i'; • return; • }

  30. Friend Functions • Program 11.6 (Continued) • // friend implementations • double addreal(Complex &a, Complex &b) • { • return(a.real + b.real); • } • double addimag(Complex &a, Complex &b) • { • return(a.imag + b.imag); • }

  31. Friend Functions • Program 11.6 (Continued) • int main() • { • Complex a(3.2, 5.6), b(1.1, -8.4); • double re, im; • cout << "\nThe first complex number is "; • a.display(); • cout << "\nThe second complex number is "; • b.display(); • re = addreal(a,b); • im = addimag(a,b); • Complex c(re,im); // create a new Complex object • cout << "\n\nThe sum of these two complex numbers is "; • c.display(); • cout << endl; • return 0; • }

  32. Operator Functions • Only the symbols in Table 11.1 can be used for user-defined purposes • New operator symbols cannot be created • Neither the precedence nor the associativity of the C++ operators can be modified

  33. Operator Functions • A user-defined operation is created as a function that redefines C++ built-in operator symbols for class use • Functions that define operations on class objects and use C++ built-in operator symbols are operator functions • Function name connects operator symbol to operation defined by function • Operator function name has format operator<symbol>

  34. Operator Functions • Program 11.8 • #include <iostream> • using namespace std; • // class declaration • class Date • { • private: • int month; • int day; • int year; • public: • Date(int = 7, int = 4, int = 2005); //constructor • bool operator == (const Date &); • // declare the operator== function • };

  35. Operator Functions • Program 11.8 (Continued) • // implementation section • Date::Date(int mm, intdd, intyyyy) • { • month = mm; • day = dd; • year = yyyy; • } • bool Date::operator==(const Date &date2) • { • if(day == date2.day && month == date2.month && year == date2.year) • return true; • else • return false; • }

  36. Operator Functions • Program 11.8 (Continued) • int main() • { • // declare 3 objects • Date a(4,1,2008), b(12,18,2001), c(4,1,2008); • if (a == b) • cout << "\nDates a and b are the same." << endl; • else • cout << "\nDates a and b are not the same." << endl; • if (a == c) • cout << "Dates a and c are the same.\n" << endl; • else • cout << "Dates a and c are not the same.\n" << endl; • return 0; • }

  37. Operator Functions as Friends • Functions in Programs 11.7 and 11.8 constructed as class members • All operator functions (except for =, (), [], ->) may be written as friend functions • Example: operator+() function from Program 11.8 • If written as friend, suitable prototype would be friend Date operator+ (Date&, int); • Friend version contains reference to Date object that is not contained in member version • Table 11.2: shows equivalence of functions and arguments required

  38. Table 11.2 Operator function argument requirements Operator Functions as Friends

  39. Operator Functions as Friends • Program 11.8’s operator+() function, written as a friend Date operator+(Date& op1, int days) { Date temp; // a temporary Date to store the result temp.day = op1.day + days; // add the days temp.month = op1.month; temp.year = op1.year; while (temp.day > 30) // now adjust the months { temp.month++; temp.day -= 30; } while (temp.month > 12) // adjust the years { temp.year++; temp.month -= 12; } return temp; // the values in temp are returned }

  40. Operator Functions as Friends • Difference between the member and friend versions of operator+()function: Explicit use of additional Date parameter (op1) • Convention for choosing between friend or member implementation: • Member function: Better for binary functions that modify neither operand (such as ==, +, -) • Friend function: Better for binary functions that modify one of their operands

  41. Operator Functions as Friends • Most operator functions can be written as friend functions • Exceptions include =, (), [], and -> • In all cases, the friend version of a member operator function must contain an additional class reference that the member function doesn’t require Table 11.2 Operator Function Argument Requirements

  42. Data Type Conversions • Conversion from one built-in data type to another discussed in Chapter 3 • Introduction of user-defined data types expands possibilities to following cases • Conversion from built-in type to built-in type • Conversion from built-in type to class (user-defined) type • Conversion from class (user-defined) type to built-in type • Conversion from class (user-defined) type to class (user-defined) type

  43. Data Type Conversions • Conversion from built-in to built-in: • Implicit conversion: Occurs in context of a C++ operation • Example: When double precision number is assigned to integer variable, only integer portion stored • Explicit conversion: Occurs when cast is used • Format dataType (expression)

  44. Data Type Conversions • Conversion from built-in to class: Done using constructor functions • Type conversion constructor: Constructor whose first argument is not member of its class and whose remaining arguments, if any, have default values • If the first argument is built-in data type, the constructor can be used to cast built-in data type to class object • Program 11.9 demonstrates this conversion type

  45. Data Type Conversions • Program 11.9 • #include <iostream> • #include <iomanip> • using namespace std; • // class declaration • class Date • { • private: • int month, day, year; • public: • Date(int = 7, int = 4, int = 2005); // constructor • Date(long); // type conversion constructor • void showDate(); • };

  46. Data Type Conversions • Program 11.9 (Continued) • // implementation section • // constructor • Date::Date(int mm, intdd, intyyyy) • { • month = mm; • day = dd; • year = yyyy; • } • // type conversion constructor from long to date • Date::Date(long findate) • { • year = int(findate/10000.0); • month = int((findate - year * 10000.0)/100.0); • day = int(findate - year * 10000.0 - month * 100.0); • }

  47. Data Type Conversions • Program 11.9 (Continued) • // member function to display a date • void Date::showDate() • { • cout << setfill('0') • << setw(2) << month << '/' • << setw(2) << day << '/' • << setw(2) << year % 100; • return; • }

  48. Data Type Conversions • Program 11.9 (Continued) • int main() • { • Date a, b(20101225L), c(4,1,1999); // declare 3 objects • cout << "\nDates a, b, and c are "; • a.showDate(); • cout << ", "; • b.showDate(); • cout << ", and "; • c.showDate(); • cout << ".\n"; • a = Date(20110103L); // cast a long to a date • cout << "Date a is now "; • a.showDate(); • cout << ".\n\n"; • return 0; • }

  49. Data Type Conversions • Conversion from class to built-in: Done by using: • Conversion operator function: Member operator function that has name of built-in data type or class • When operator function has built-in data type name, it is used to convert from class to built-in data type • Usage of this type of function demonstrated in Program 11.10

  50. Data Type Conversions • Conversion from class to class: Done using member conversion operator function • Same as cast from user-defined to built-in data type • In this case, operator function uses class name being converted to rather than built-in data name • Demonstrated in Program 11.11

More Related