0

I already searched everywhere and I think this is really basic problem but I checked some other people code and they were using the same method to create an object with a unique ID that's why I'm not understanding why it doesnt work with me.

So here's the class Enemy:

class cEnemy{
public:
       //code that doesnt matter
};

So what i want to do is basically create 10 Enemies and each one will have a unique identifier(0...9), so what im doing is:

for (int i = 0; i < 10; i++){
       Enemy[i] = new cEnemy;
}

Right now it already gives me an error: error C2065: 'Enemy' : undeclared identifier

But if instead of writing Enemy[i] if i write Enemy[5] it works fine. I think im missing something.

Why? I saw this code exactly the same in other application and it works...

So my objective as I said it's to create 10 enemies with unique Id's and then to have access to each one but as you see i can't even create them.

Thanks in advance.

PS: The class and main are in the same cpp file

1 Answer 1

1
std::array<cEnemy, 10> Enemy;
for(int i = 0; i<10; ++i) {
    Enemy[i] = new cEnemy;
}

You have to create an array before you can use it. The error you're getting is the same as if you were try to do:

arrInt[i] = someInt;

Before having done:

int arrInt[someCount];
Sign up to request clarification or add additional context in comments.

3 Comments

You're correct of course, but I'd advise using a std::array<cEnemy, 10> (or a vector) to avoid all the horrible pointer decay things that happen when passing C arrays to functions, which can be pretty confusing to newcomers.
@nhgrif Thanks a lot. So to be sure if i understood, with that code we created an array that has 10 objects of the type cEnemy, and with the for cycle, in each position of the array we make a new enemy? Let's say that the Enemy has X position and I want to access the position of the enemy saved in array with "id" 5: I just need to do this? Invasor[5]->getX(); Im a little confused
Well, in this example, the array is called Enemy. But if your cEnemy class has a method called getX(), and you want to call that on an element of the array, then I believe you've got the right syntax: Enemy[5]->getX(); I'm not perfectly familiar with C++, so no guarantees, but try it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.