1

I am trying to dynamically allocate array of objects. I have a class Enemy in my project and I'd like to create 5 enemies. After exhausting research I can't get answer for my problem.

Enemy* mainEnemy = new Enemy(enemyShip)[5];

There is an error : no suitable conversion from Enemy to Enemy* exists.

When I deleted the pointer, there is no errors in this line :

 Enemy mainEnemy = new Enemy(enemyShip)[5];

But how can I work with objects created like this? I can't set position of single object like that:

mainEnemy[0]->StartingPosition(); // no operator "[]" matches these operands . operand types are: Enemy[int]
4
  • What is enemyShip? What are you trying to accomplish with new Enemy(enemyShip)[5];? Allocate an array of 5 enemies, all of which are constructed from enemyShip? Commented Dec 5, 2020 at 23:15
  • enemyShip is a ship class instantion . ship* enemyShip = new ship(&enemyT); Class ship takes enemy texture as parameter and class enemy takes pointer to ship as parameter. I just want to dynamically allocate 5 enemies, make operations on them (drawing, setting position etc.I am trying to create an array with these objects. Commented Dec 5, 2020 at 23:26
  • 1
    I am trying to dynamically allocate array of objects. -- std::vector<Enemy> mainEnemy(5, enemyShip); Commented Dec 5, 2020 at 23:44
  • You need to post a minimal reproducible example. First, that &enemyT is suspicious, as we don't know where or when this enemyT object is created or its lifetime. Needless to say, storing addresses of anything means that you need to make sure that whatever you're storing the address of must not go out of scope during the time you are accessing this address. Commented Dec 6, 2020 at 2:08

1 Answer 1

1

Recommendation: Consider using a vector.

const size_t NUM_ENEMIES{ 5 };
std::vector<Enemy*> enemies(NUM_ENEMIES, new Enemy(enemyShip));

Your Question: If you want to dynamically create an array of 5 enemies.

const size_t NUM_ENEMIES{ 5 };
Enemy* enemies[NUM_ENEMIES]{};
for( int x=0; x < NUM_ENEMIES; ++x )
{
    enemies[x] = new Enemy(enemyShip);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your two code snippets don't achieve the same result. In the first case there are five pointers but only one Enemy. In the second there are five pointers and five enemies. In the absense of any other information the best answer would be not to use any pointers at all std::vector<Enemy> enemies(NUM_ENEMIES, enemyShip);

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.