jeudi 21 mars 2019

How to modify a composition of objects from within the objects

If you have a class that is composed of other sub-classes, how do you make it so that if you modify a property of the sub-class, that change is reflected in the composition class? (Sorry of this is a basic question, I'm not great with objects)

For example, say I have a Meal composed of two Sandwich objects. Both the meal and the sandwiches have calorie variables, but if I add some cheese to one of the sandwich objects, I want this to somehow update the number of calories in the meal. Is there a good way to achieve this?

In the following (C++) code, for example, adding cheese to the main course doesn't update the calories in the meal. (By the way, I have no idea how many calories is in actual food)

#include <iostream>

struct Sandwich
{
    int calories = 0;

    Sandwich(int calories): calories {calories} {}

    void AddCheese() { calories += 50; }
};

struct Meal
{
    Sandwich entree;
    Sandwich main;
    int calories = 0;

    Meal(const Sandwich& entree, const Sandwich& main)
    : entree {entree}, main {main}, calories {entree.calories + main.calories}  {}
};

int main()
{
    Sandwich toastie(500);
    Sandwich hoagie(1500);

    Meal lunch(toastie, hoagie);

    lunch.main.AddCheese();

    std::cout << "lunch.entree.calories = " << lunch.entree.calories << std::endl;     
    std::cout << "lunch.main.calories = " << lunch.main.calories << std::endl; 
    std::cout << "lunch.calories = " << lunch.calories << std::endl; 

    return 0;
}

Output:

lunch.entree.calories = 500
lunch.main.calories = 1550
lunch.calories = 2000

Aucun commentaire:

Enregistrer un commentaire