Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 1 month ago

In C++ how to print out all the class objects made in the main function with a pointer?

I am working on a small project of creating a mocha creation menu in C++. Base class is called Mocha and comes with public instance variables and public classes to set/get the values of the instance variables as well as a virtual pure prepare function which gets all the variables a person sets and displays the results. There are three child classes to that class called White chocolate, Dark chocolate and peppermint and they all override the prepare function.

The menu in the int main() function runs in a basic while loop and a case-switch loop where you choose a number based off the mocha you want, input the amount you want for each ingredient and then the results are displayed. The object used to create these mocha class objects is Mocha* coffee and this 'coffee' is used in every option.

My question is, how can I display all of those mocha objects made with another option using that pointer for coffee?

Code is here in one cpp file (no headers): https://easyupload.io/uh7qen

Update:

Best answer gets 5 stars from me!

1 Answer

Relevance
  • 1 month ago
    Favorite Answer

    Nothing in C++ keeps track of objects created using the "new" operator, so you have to do that yourself.  One quick solution is to make a std::vector<Mocha*> object that keeps a list of pointers to the objects you've created. 

    std::vector<Mocha*> all_orders;

    Then you can use something like:

    coffee = new DarkChocolate(...args...);

    all_orders.push_back(coffee);

    coffee = new WhiteChocoloate(...args...);

    all_orders.push_back(coffee);

    At any point, you can use all_orders like a pointer array.  A really simple way to print all of them out in order of creation is:

    for (Mocha *mp : all_orders)

    {

        std::cout << mp-->getChocolateType() << std::endl;

    }

    At some point you might find it useful to have a virtual function defined in Mocha that's implemented in each derived class to return a one-line description of the order as a string.  I just used getChocoloateType() for that purpose since it's the closest you have in that source file.  It doesn't include any customization, like shots/pumps/etc. though.

    Farther down the road, plan to learn how to use the "smart pointer" types defined in <memory> to manage dynamic objects and avoid things like memory leaks and dangling pointers.

    • Log in to reply to the answers
Still have questions? Get answers by asking now.