110 likes | 259 Views
Department of Computer and Information Science, School of Science, IUPUI. Classes this & pointers to members. CSCI 240. Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu. Self-Reference -- this.
E N D
Department of Computer and Information Science,School of Science, IUPUI Classesthis & pointers to members CSCI 240 Dale Roberts, Lecturer Computer Science, IUPUI E-mail: droberts@cs.iupui.edu
Self-Reference -- this • A Pointer to the Object, which is Used in Member Function Invocation -- this • A Return Pointer to that Object • Direct Reference to Members of the Object in a Member Function is Possible • this is NOT Available to friend Functions
this – Example 1 • class student{ int ss; public: int readme(){return ss;} int explicit_readme(){return this->ss;} }; • void my_function(student s1, student s2){ /* Implicit Presence of "this" */ int a = s1.readme(); //Call "readme()" refers to "s1". int b = s2.readme(); //Call "readme()" refers to "s2". • /* Explicit Presence of "this" */ a = s1.explicit_readme(); b = s2.explicit_readme(); }
this -- Example 2 • /* Use of "this" in a doubly linked list */ class student{ int ss; student *next; student *prev; public: void append(student *); };
this -- Example 2 • void student::append(student *ip){ ip->next = next; ip->prev = this; next->prev = ip; next = ip; } • void my_function(student *new_student){ student *head; // ... head->append(new_student); }
ss3 ss2 ss1 ss4 prev prev prev prev next next next next this -- Example 2 Before configuration head (this) ip
ss1 ss3 ss2 ss4 prev prev prev prev next next next next this -- Example 2 After configuration Head (this) void student::append(student *ip){ ip->next = next; ip->prev = this; next->prev = ip; next = ip; ip
Pointers to Members • Pointers to Data Members • Pointers to Member Functions
Pointers to Data Members -- Example • class student{ public: int ss, credits; student():ss(0), credits(0){} }; • main(){ int student::*psi; // "psi" is a pointer to an integer psi = &student::ss; // "psi" is pointing to "ss" student s1; s1.*psi = 1; //s1.ss = 1 student *ptr = new student; ptr->*psi = 2; //ptr->ss = 2 psi = &student::credits; // "psi" is pointing to "credits" s1.*psi = 3; //s1.credits = 3 }
Pointers to Member Functions -- Example • class student{ public: int ss, credits; student():ss(0), credits(0){} int return_ss(){return ss;} int return_credits(){return credits;} }; • main(){ // "pmf" is a pointer to a member function of "student" that returns int int (student::*pmf)(); pmf = student::return_ss; // "pmf" is pointing to "return_ss()" student s1; cout << (s1.*pmf)() << endl; //"s1.return_ss()" is invoked pmf = student::return_credits; // "pmf" is pointing to "return_credits()" cout << (s1.*pmf)() << endl; //"s1.return_credits()" is invoked }
Acknowledgements • These slides were originally prepared by Rajeev Raje, modified by Dale Roberts.