Search code examples
c++arraysdynamic-arrays

Why can't one dynamically declare an array of objects in C++ like this :


In my C++ project, there is a class which needs to create an array of objects. Between different instances of the class, the size of the array will be different, which is why I chose to use an array.

If I do :

int numberOfPlayers; // This is determined at run time.
int *players; 

//In constructor
players= new int[numberOfPlayers]; // This works

But if I do:

Character *players;
players = new Character[numberOfPlayers]; // Compiler complains

The Compiler complains "No matching constructor for initialisation of Character"

How do I dynamically declare an array of type "Character".

Note: Character has nothing to do with char. Character is a name of an class I created myself.

EDIT: Character does not have a default constructor, since it needs to be passed several arguments so it can be initialised with the proper state. The only constructor is has takes several arguments.

EDIT: I chose a dynamically created array, over a vector since I know during the lifetime of the instance, the size of the array will be constant, though between different instances the size will be different. I thought this would make sense for performance reasons (memory / speed).


Solution

  • The "proper" way is to use std::vector. It is a fast, safe, more robust alternative to horrible new.

    std::vector<Character> vec;
    vec.push_back(Character(params));
    vec.push_back(Character(other_params));
    

    If you know the size ahead, you can avoid reallocation overhead by using std::vector::reserve

    std::vector<Character> vec;
    vec.reserve(50);
    vec.push_back(Character(params));
    vec.push_back(Character(other_params));
    

    The overhead of std::vector is practically non-existent.

    Now, the reason why you can't do this your way, it's because by default new uses default constructor, and it doesn't exist.