I'm tring to create Card and Deck classes but I'm getting an error message that says
Allocation of incomplete type 'Card'
The problem is happening in Deck::Deck() of Deck.cpp
//
//Deck.h
#ifndef JS_DECK_H
#define JS_DECK_H
#include <iostream>
using std::cout;
#include <vector>
using std::vector;
//forward declaration
class Card;
namespace JS {
class Deck {
public:
Deck();
private:
vector<Card *>cards;
};
}
#endif
//
//Deck.cpp
#include "Deck.h"
using namespace JS;
Deck::Deck(){
for(int suit = 0; suit < 4; suit++){
for(int rank = 1; rank < 14; rank++){
cards.push_back(new Card(rank, suit));//allocation of incomplete type 'Card'
}
}
}
//
//Card.h
#ifndef JS_CARD_H
#define JS_CARD_H
#include <ostream>
using std::ostream;
#include <string>
using std::string;
#include <vector>
using std::vector;
namespace JS {
class Card {
friend ostream &operator<<(ostream &out, const Card &rhs);
public:
enum Suit { DIAMONDS, HEARTS, SPADES, CLUBS };
enum Rank { ACE = 1, JACK = 11, QUEEN = 12, KING = 13 };
Card(int rank, int suit) : rank(rank), suit(suit){}
string getRank() const;
string getSuit() const;
int getRankValue() const;
int operator+(const Card& rhs);
void displayCard(const Card &rhs);
private:
int rank;
int suit;
};
}
#endif
An incomplete type is a type the size (i.e. the size you'd get back from sizeof ) for which is not known. Another way to think of it is a type that you haven't finished declaring. You can have a pointer to an incomplete type, but you can't dereference it or use pointer arithmetic on it.
An incomplete class declaration is a class declaration that does not define any class members. You cannot declare any objects of the class type or refer to the members of a class until the declaration is complete.
This error usually means that you are trying to follow a pointer to a class, but the compiler did not find the definition of that class (it found a declaration for the class, so it is not considered an unknown symbol, but it did not find a definition, so it is considered an incomplete class).
In the implementation of Deck
(i.e. the Deck.cpp
file) you need the full definition of Card
to be able to allocate objects of that type. So the solution is simply to include Card.h
in Deck.cpp
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With