|
|
|
|
|
|
|
|
|
|
|
|
The ClassName variable was intended to simply contain the name of the class, so rather a technical variable. I guess one could also just leave this one out, as I don't see any specific purpose for the RPG. What do you think? |
At the beginning I want to make a query for the user to chose a hero, obviously, so I made a switch statement. This works fine, however, when I want to instantiate the chosen object, let's say a warrior, I do as follows: 1 2 3 4 5 std::string name; std::cin >> name; if (character == 'a') { Warrior* warrior = new Warrior(name); } , where 'character' denotes the char variable to chose between the heroes (a,b,c,d). I have to use an if statement here, also for obvious reasons. My problem is that I cannot use the hero now out of scope, as it is instantiated within an if statement. What is the common, elegant way to get this done? Do I have to stay within this if statement for the rest of the RPG? That seems a bit inappropriate to me. |
|
|
|
|
I have to use an if statement here |
push_back
or emplace_back
objects of the derived classes. This and other vectors then becomes a parameter to the constructor of the character being created, thereby having less parameters.push_back
or constructed in place with emplace_back
into it.new
, it's bad news because if an exception is thrown, neither the delete
or the destructor is reached and memory is leaked. Prefer to use STL containers like std::vector
which does it's own memory management on the heap efficiently and embracing the RAII concept. There are also smart pointers like std::unique_ptr which can be used with virtual polymorphism.new
is for your own implementation of a list, or if you were making your own container like here, I call it an XMas Tree: