I have declaring instances of my equipment class everytime I need to use it. Is there a way I can use a function to do it so I don't have to remember everytime what the specifics of that object were and use the function to create the object then use it in a different function? something like this?
I know I can't use it for cin and cout, I just want to create one function for creating the object, so I don't have to retype it everytime. I'm not sure if that makes sense or is possible.
// ...
sword* player::createSword()
{
returnnew sword("Sword", 2, 0);
}
// ...
int main()
{
player player1( ... );
sword* a_sword = player1.createSword();
some_func( a_sword );
delete a_sword; // <-- do not forget this
}
Or a more safer way is :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <memory>
// ...
std::unique_ptr<sword> player::createSword()
{
return std::unique_ptr<sword>( new sword("Sword", 2, 0) );
}
// ...
int main()
{
player player1( ... );
auto a_sword = player1.createSword(); // a_sword's type is unique_ptr
some_func( a_sword );
//delete a_sword; // <-- not needed, the destructor of unique_ptr<> automatically frees memory allocated by new
}