Download
static variables and the this pointer n.
Skip this Video
Loading SlideShow in 5 Seconds..
Static Variables and The this Pointer PowerPoint Presentation
Download Presentation
Static Variables and The this Pointer

Static Variables and The this Pointer

69 Vues Download Presentation
Télécharger la présentation

Static Variables and The this Pointer

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. B Smith: Score: 2. The Borg analogy was illuminating for static variables. Most was dry. B Smith: Some of this code had errors. Type all in and verify. sp06. This was last slide of Sp06 and took 2 lectures. Rate: 3 of 4.` Static Variables and The this Pointer B Smith: Sp06: spent an entire class building up an initialization list by hand, then remainder on a final exam problem. Stopped at slide 7. Math 130

  2. Topics • Base Member Initialization • Static member variables • Static member functions • The thispointer • Booleans

  3. B Smith: See project 6 discussion Class Member Values: Constructor class Date{ private: int _month, _day, _year; public: Date( int=7, int=4, int=2001 ) ; // constructor prototoype w/ default vals . . . } Date::Date(int mm,int dd,int yyyy ) //constructor implementation { _month = mm; _day = dd ; _year = yyyy ; }

  4. Class Member Values: Init’lzn List class Date{ private: int _month, _day, _year; public: Date( int=7, int=4, int=2001 ) ; // constructor prototoype . . . } Date::Date(int mm,int dd,int yyyy ) : _month(mm),_day( dd ),_year( yyyy ){}

  5. Default Values and Initialization List class Date{ private: int _month, _day, _year; public: Date( int mm =7, int dd=4, int yyyy=2001 ) : _month(mm),_day( dd ),_year( yyyy ){} . . . } class Date{ private: int _month, _day, _year; public: Date( int mm, int dd, int yyyy ) : _month(mm),_day( dd ),_year( yyyy ){} . . . }

  6. Default Values and Initialization List, w/ Verification class Date{ private: int _month, _day, _year; public: Date( int mm, int dd, int yyyy) : _month(mm),_day(dd),_year(yyyy){ if( mm > 0 && mm <= 12) _month = mm; else { _month = 1; cout << “invalid entry for month. Month set to Jan. } //end else _year = yyyy; _day = verifyDate(dd); // e.g., disallow 35 days in a month } // end Date constructor . . .

  7. B Smith: Start off with pix of borg. Stick figures ok. Show 4 and but keep out the BorgCount. Static Class Members • Each class object normally has its own memory space • There is also a means for having objects of the same class share a variable (or a function) • C++ calls this shared item a static variable • The net effect is a “global” variable for the class

  8. B Smith: Too wordy. Use pictures B Smith: discussion on protected should be postponed! Static Class Members • static class members • Shared by all objects of a class • Normally, each object gets its own copy of each variable • Efficient when a single copy of data is enough • Only the static variable has to be updated • May seem like global variables, but have class scope • Only accessible to objects of same class • Initialized at file scope • Exist even if no instances (objects) of the class exist • Can be variables or functions • public, private, or protected B Smith: print this one for handout, but do not display

  9. Static Class Members • public staticvariables: • accessible through any object of the class • Use class name and (::) eg Employee::count • private static variables: • a public static member function must be used. • Prefix with class name and (::) eg Employee::getCount() • staticmember functions cannot access non-static data or functions

  10. Static Member Data • No matter how many Employee objects are created, the declaration below establishes one taxRate // class declaration class Employee { private: static float taxRate; int idNum; public: Employee(int); // constructor void display(); // access function }; // static member definition float Employee::taxRate = 0.0025;

  11. B Smith: verify this one Static Member Functions • These functions are for the entire class, not just an instance or an individual object • Can only access static data members and other static member functions of the class // class declaration class Employee { private: static float taxRate; int idNum; public: Employee(int); // constructor void display(); // access function static void disp(); // static function };

  12. B Smith: Static member functions have no “this”. Hence, it cannot access ordinary members. #include <iostream> // class declaration class Employee { private: static float taxRate; int idNum; public: Employee(int); // constructor void display(); // access function static void disp(); // static function }; // static member definition float Employee::taxRate = 0.0025; // class implementation Employee::Employee(int num = 0) { idNum = num; } void Employee::display() { cout << "Employee number " << idNum << " has a tax rate of " << taxRate << endl; } void Employee::disp() // can only see static variables { cout << "The static tax rate is " << taxRate << endl; } B Smith: Every static variable must be init’lzd outside the class def. It cannot be init more than once Every static variable must be init’lzd outside the class def. It cannot be init more than once B Smith: Why do we need both disp() functions? Must explain better! Sp06: See later notes for a good answer!

  13. B Smith: Good slide. Introduces ideas without the complexities. Different Object, Same Data int main() { Employee::disp(); // call the static functions Employee emp1(11122), emp2(11133); emp1.display(); emp2.display(); return 0; }

  14. B Smith: Place this info with earlier lecture on overloaded operator The this pointer • Class instances contain their own set of member variables • The member variables can be thought of as a struct data type • Since static variables are not instance (or class) variables, they are not part of the “structure” • Each object is distinct with its own “state”

  15. B Smith: This slide doesn’t help much The this pointer • Recall pointers to structures struct Employee /* declare a global structure type */ { int idNum; double payRate; double hours; }; double calcNet(struct Employee *); /* function protoytpe */ int main() { struct Employee emp = {6782, 8.93, 40.5}; struct Employee emp2 = {2382, 12.28, 45}; double netPay; netPay = calcNet(&emp); /* pass an address */ printf("The net pay for employee %d is $%6.2f\n",emp.idNum,netPay); return 0; } double calcNet(struct Employee *pt) /* pt is a pointer to a */ /* structure of Employee type */ { return(pt->payRate * pt->hours); }

  16. B Smith: little confusing. Must show pictures B Smith: this The this pointer • emp and emp2 are stored similarly in memory • C++ classes also provide distinct memory allocation for class member variables (non static) • But class member functions are shared entities • How was calcNet() able to determine which employee it was working on? • The address of the data structure, the object, was explicitly passed to the function!

  17. void Date::showdate() { cout << setfill(’0’) << setw(2) << _month <<’/’ << setw(2) << _day <<’/’ << setw(2) << _year % 100 << endl; return; } How does showdate know which object? An implicit address is passed int main ( ) { Date a(4,1,1999), b(12,18,2001); //declare two objects a.showdate(); // display a’s date b.showdate(); // display b’s date return 0 ; }

  18. B Smith: R Yu had a good question: Can we use Date& this instead??? The this pointer • In C++, member functions are also passed an address • The address is stored in a special pointer, named this • this is automatically supplied, “behind the scenes” • Hence, our parameter list of Date... Date::Date(int mm,int dd,int yyyy ) { . . . } Date::Date(Date *this,int mm,int dd,int yyyy ) { . . . }

  19. B Smith: Point out that this.month is not correct The this pointer • Since a pointer to the object is “passed,” we could actually rewrite the constructor function: Date::Date(int mm, int dd, int yyyy ) { _month = mm; _day = dd; _year = yyyy; } Date::Date(Date*this,int mm, int dd, int yyyy) { this->_month = mm; this->_day = dd; this->_year = yyyy; }

  20. Also, for showdate() void Date::showdate(Date*this) { cout << setfill(’0’) << setw(2) << this->_month <<’/’ << setw(2) << this->_day <<’/’ << setw(2) << this->_year % 100 << endl; return; }

  21. The this pointer • Recall that we overloaded operator, = • It performed memberwise assignment, but returns no value • We MUST have return value means to do: a = b = c; void Date::operator=(Date &newdate ) //Note the void { _day = newdate._day; // assign the day _month = newdate._month; // assign the month _year = newdate._year; // assign the year }

  22. The this pointer • The assignment operator revisited – see pgm 14.9 • The fix is simply to return the object: Date Date::operator=(Date& newdate ) // Returns a Date { _day = newdate._day; //assign the day _month = newdate._month; // assign the month _year = newdate._year ; // assign the year return *this ; } Remember to change the prototype!

  23. B Smith: Students caught on to this idea easily B Smith: Fix the pop-up: It’s inconsistent with the comment. Booleans • A variable of type Boolean can have one of two values, true or false • Booleans are used to express the result of logical operations B Smith: //#include <stdio.h> #include <iostream> int main() { std::cout << sizeof(bool) << std::endl; system("pause"); return 0; } void f(int a, int b) { bool b1; int x; b1 = (a==b); if (b1 == true) cout << “true indeed” << endl; //… }

  24. Boolean • By definition, true has the value 1 when converted to an integer, and false has the value 0 • Integers can be implicitly converted to bool values • nonzero integers convert to true, 0 converts to false. bool b =7; int i = true; cout << "bool b is: " << b << endl; cout << "int i is: " << i << endl;