Search code examples
c++stdarray

Cannot create constructor with std::array<T, n> as class member


Here the code

#include "card.h"
#include <array>

constexpr int DECK_SIZE = 52;

class Deck {
    std::array<Card, DECK_SIZE> m_deck; 
public:
    Deck();
    ~Deck() = default;
    Card getCard(int index) { return m_deck[index]; }
};

Card is just another class, not relevant here. I want to create Deck constructor now, which will just create 52 Card objects and assign it to my array. Although, when I go to Deck.cpp and start doing this

#include "deck.h"

Deck::Deck() {    
}

I got error that I reference deleted function

'std::array::array(void)': attempting to reference a deleted function

I dont really understand, array size is known at compile time, now I just want to create objects and assign it to this array, why I cant do that?

Didnt realize that Card is actaully relevant in this case, anyways here is the code

#include <SFML/Graphics.hpp>

constexpr auto FILE_PATH = "res\\cards\\";

class Card {
    char m_rank;
    char m_suit;
    int m_value;
    sf::RectangleShape m_shape;
    sf::Texture m_texture;
public:
    Card(char, char, int, std::string);
    ~Card() = default;

    char getRank() { return m_rank; }
    char getSuit() { return m_suit; }
    int getValue() { return m_value; }
    void setValue(int p_value) { m_value = p_value; }
    sf::Texture getTexture() { return m_texture; }
    sf::RectangleShape getShape() { return m_shape; }
    void setPosition(float p_x, float p_y) { m_shape.setPosition(p_x, p_y); }
};

Card::Card(char p_rank, char p_suit, int p_value, std::string p_texture_file_name)
    :m_rank(p_rank), m_suit(p_suit), m_value(p_value) {
    m_texture.loadFromFile(FILE_PATH + p_texture_file_name);
    m_shape.setSize((sf::Vector2f(70, 90)));
    m_shape.setTexture(&m_texture);
}

Solution

  • In order to default-construct std::array<Card, DECK_SIZE>, Card must be default-constructible. Your Card class is not.