C++ Class this Passing an Object from Inside Its Member Functions

Description

C++ Class this Passing an Object from Inside Its Member Functions

#include <iostream>

using namespace std;

class Food/* ww  w.j  a  va  2s.  c om*/
{
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;
}



PreviousNext

Related