+1

[C++] Trying to play around with classes

Sup there So i'm pretty new to OOP and i'm trying to play around with it I have done a mini shooting game around 2 player from the class made : https://pastebin.com/6m6NjYai I'm pretty noob so you guys have some ajustement to do. Btw if like the player want to add another player, do i need to create another string that store the player3 name then create a p3.name from that or i can do it directly from what the player typing ? like (p3.name = cin ?) I did not make the player 2 interact yet he he just here to take damages.

8/10/2019 10:40:44 AM

Charles C

9 Answers

New Answer

+1

Charles C directly read p3.name cin >> p3.name;

+3

Charles C in case life can be set and get like in ~ swim ~ example, yes, even though some would say it is not a good way of doing. In case it has rules to be set, no

+2

Charles C if you write players p1, players p2 outside of main (above main) then they are global objects and can be accessible from anywhere in your code. I suggest refactor the code. class Player{ public: Player(string name, int id) : pname(name), pid(id) {} // provide getter for all fields getname, getid, getlife, getdamage // provide setter for setlife, setdamage private: string pname; int pid; int life = 100; int damage = 20; }; // outside main Players* p1 = nullptr; Players* p2 = nullptr; object creation in main string name; cin >> name; p1 = new Player(name, 1); cin >> name; p2 = new Player(name, 2); // access properties by arrow operator p1->getlife(), p1->setlife(x); in the end before exiting main free the resources delete p1; delete p2;

+1

@~ swim ~ And how can i make my player object global ? Like if i create another function. How can i call p1 created on the main on it ?

+1

Charles C Yes you have to write them in public section like public: // getter for life int getLife() { return life; } // setter for life void setLife(int val) { life = val; } then in the main code cout << p1->getLife(); p1->setLife (90);

+1

Charles C Faster? A little bit probably microsecond difference. But then you are using C++ as better C and in that case a plain C style struct would suffice, infact you are using the class that way, better use a struct , you don't have to write explicit public section, everything is public by default. You don't have to use what i suggested. What i suggested was more of oops way of doing things.

+1

@~ swim ~ Yeah i come from C and objet is not really clear for me yet. But as far as i know they are more useful than struct

0

~ swim ~ i dont get are get and set function.

0

Isnt is just faster to put the life in public and just p1.life ?