I have the class Flashcard
declared in Flashcard.h
and Flashcard.cpp
. I want to make a class CardList
which should store a std::vector<Flashcard>
as well as some other information, and provide some methods for manipulating it.
CardList.h
#include <vector>
#ifndef LC_FLASHCARD
#include "Flashcard.h"
#endif
class CardList
{
public:
/* Constructor */
CardList (int number_of_cards = 1);
/* Returns the j'th card. */
Flashcard getCard ( int j );
/* Replaces the j'th card with new_card. */
void setCard ( int j, Flashcard new_card );
/* ... */
private:
std::vector<Flashcard> card_list;
/* ... */
};
CardList.cpp
#include "CardList.h"
CardList::CardList ( int number_of_cards ) {
std::vector<Flashcard> card_list(number_of_cards);
}
CardList::~CardList ( void ) { }
Flashcard CardList::getCard ( int j ) {
return this->card_list[j];
}
void CardList::setCard ( int j, Flashcard new_card ) {
this->card_list[j] = new_card;
}
Flashcard CardList::drawCard ( void ) {
return this->getCard(0);
}
The problem
Whenever I call CardList::getCard
or CardList::setCard
, I get a segfault. For example:
#include "Flashcard.h"
#include "CardList.h"
/* ... */
int main( int argc, char** argv ) {
/* Creates flashcard card */
Flashcard card;
/* (do things to card) */
CardList card_list(7);
std::cout << "Declaration and initialisation of card_list successful" << std::endl;
card_list.setCard(0, card); // *** SEGFAULT ***
std::cout << "Assignment successful" << std::endl;
/* ... */
return 0;
}
I think the problem is with my constructor CardList::CardList
, but how do I fix it?