Passing an Object from Inside Its Member Functions by Using the this Variable - C++ Class

C++ examples for Class:this

Description

Passing an Object from Inside Its Member Functions by Using the this Variable

Demo Code

#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;
}

Result


Related Tutorials