Search code examples
c++dynamicobject

How to create objects dynamically?


I am new to coding, I'm trying to learn C++. I am making a roulette game, and I am trying to use classes and objects. I have a class called Bets, that stores the players bet choice in an object, it could be a number, or an outside bet like odd or even. This works fine, but I would like to give the user the option to place multiple bets in the same spin, so when the user answers yes to the question, "Place another bet?", I would like another object to be made. Could someone please help me create multiple objects of the same class?


Solution

  • The keyword new lets you create a new object. C++ is a little different than a language like .Net or Java, if you are familiar with those languages. The C++ languages uses the keyword new, but new return a "pointer" to the new object. If your class is named "Bet", then the statement:

    Bet *betPointer = new Bet();
    

    Will create a new "Bet" object and assign its pointer to the variable "betPointer".

    If bet has a property names "color" that return a string, then instead of writing:

    betPointer.color //this is wrong
    
    betPointer->color //this is correct.
    

    My favorite site to research these kinds of questions is http://www.cplusplus.com. Follow this link for a more information and examples using the keyword new: http://www.cplusplus.com/reference/new/operator%2k0new/