Home > Blockchain >  storing and working with multiple objects of the same class in c
storing and working with multiple objects of the same class in c

Time:02-20

I'm sure there is a simple solution for this but i'm having trouble working out what the best option is. Say the for example I have a class called entity that looks like this:

class Entity
{

public:
int health;
int strength;

};

This is obviously a very simple class but my problem is when it comes to creating each object. If I am trying to make a game or whatever where I have lots of different types of entity's with different values for health and strength. What is the best way to organize the declaration of all these variables so that I don't end up with something that looks like this:

Entity cat;
cat.health = 6;
cat.strength = 10;

Entity dog;
dog.health = 10;
dog.strength = 15;

Entity wolf;
wolf.health = 17;
wolf.strength = 25;

This is already looks kind of messy but it gets even worse with more objects or objects with more variables to declare. What is the best way around something like this i've been struggling to figure it out.

CodePudding user response:

The answer you're looking for is encapsulation. Instead of having all your variables be public and assigning values to them one-by-one, you could try something like this:

class Entity 
{
    private: int health;
    private: int strength;

    public: 
    Entity(int h, int s) //constructor
    {
        health = h;
        strength = s;
    } 
};

and then calling it like so:

Entity cat(15,16);

You could also use separate setter functions but a constructor is the easiest way to go.

CodePudding user response:

As long as the Entity class is kept simple and doesn't require a custom constructor for other purposes, you can initialize the objects like this:

    Entity cat { .health = 9, .strength = 2 };
    Entity dog { .health = 1, .strength = 3 };

which might be more readable compared to the constructor method because you keep the variable names.

CodePudding user response:

To store many objects you want to use container. As your objects are identified by names, dog, cat and wolf, a map can be used:

#include <string>
#include <map>
#include <iostream>

struct Entity {
    int health;
    int strength;
};

int main() {
    std::map<std::string,Entity> entities;
    entities["cat"] = {6,10};
    entities["dog"] = {10,15};
    entities["wolf"] = {17,25};

    for (const auto& e : entities){
        std::cout << e.first << " health: " << e.second.health << " strength: " << e.second.strength << "\n";
    }
}

Output:

cat health: 6 strength: 10
dog health: 10 strength: 15
wolf health: 17 strength: 25

Using strings as keys is not necessarily the best option, its just to demonstrate what can be done. For example if the number of entities is fixed you could use an enum entity_type { dog,cat,wolf} as key. Alternatively the name could be a member of Entity and you can use a std::vector<Entity> to store them.

  • Related