C++ examples for Class:this
Passing an Object from Inside Its Member Functions by Using the this Variable
#include <iostream> #include <string> using namespace std; class Food// w w w.j a va 2s . com { public: string status; void eat(); void rot(); }; int FoodCount; void OneMoreFoodGone(Food *Block) { FoodCount--; Block->status = "Gone"; }; void Food::eat() { cout << "Eaten up! Yummy" << endl; OneMoreFoodGone(this); } void Food::rot() { cout << "Rotted away! Yuck" << endl; OneMoreFoodGone(this); } int main() { Food *f1 = new Food(); Food *f2 = new Food(); FoodCount = 2; f1->eat(); f2->rot(); cout << endl; cout << "Food count: " << FoodCount << endl; cout << "f1: " << f1->status << endl; cout << "f2: " << f2->status << endl; return 0; }