Download presentation
Presentation is loading. Please wait.
1
How Classes Work with Memory Diagram
CSCE 121
2
output identifier stack
int main() { Date w(7, 7, 2015); // constructor w.setDay(4); // mutator w.printDate(); } identifier stack
3
class Date { int month; int day; int year; public: // constructors Date(); Date(int month, int day, int year); // accessors and mutators int getMonth(); void setMonth(int month); int getDay(); void setDay(int Day); int getYear(); void setYear(int year); // methods void printDate(); };
4
output identifier stack
int main() { Date w(7, 7, 2015); // constructor w.setDay(4); // mutator w.printDate(); } month main day w year identifier stack
5
output identifier stack implicit parameter ‘this’
Date::Date(int month, int day, int year) : month(month), day(day), year(year) {} implicit parameter ‘this’ year 2015 day 7 Identifier resolution First look for local version from parameter or local variable Second, prepend with ‘this->’ to associate with object and try again Date month 7 this month 7 main day 7 w year 2015 identifier stack
6
output identifier stack
int main() { Date w(7, 7, 2015); // constructor w.setDay(4); // mutator w.printDate(); } year 2015 day 7 Date month 7 this month 7 main day 7 w year 2015 identifier stack
7
output identifier stack
void Date::setDay(int day) { if (day>=1 && day<=31) { this->day = day; } else if (day < 1) { this->day = 1; else if (day > 31) { this->day = 31; day 4 setDay this year 2015 day 7 Date month 7 this month 7 main day 4 w 7 year 2015 identifier stack
8
output identifier stack
int main() { Date w(7, 7, 2015); // constructor w.setDay(4); // mutator w.printDate(); } day 4 setDay this year 2015 day 7 Date month 7 this month 7 main day 4 w 7 year 2015 identifier stack
9
output identifier stack Recall: Identifier resolution
void Date::printDate() { cout << month << "/" << day; cout << "/" << year << endl; } 3/25 /2019 Recall: Identifier resolution First look for local version from parameter or local variable Second, prepend with this-> to associate with object and try again printDate this day 4 setDay this year 2015 day 7 Date month 7 this So body essentially becomes: cout << this->month << "/" << this->day; cout << "/" << this->year << endl; month 7 main day 7 4 w year 2015 identifier stack
10
output identifier stack
int main() { Date w(7, 7, 2015); // constructor w.setDay(4); // mutator w.printDate(); } 3/25 /2019 printDate this day 4 setDay this year 2015 day 7 Date month 7 this month 7 main day 4 w 7 year 2015 identifier stack
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.