Initializing array

Hello guys,

This question may be very simple, yet difficult for me as a C++ beginner.

I have a class called Deck, and I want to allocate memory for the array Deck because there have to be 52 Card objects in it.

How should I do it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#ifndef DECK_H
#define	DECK_H

#include <iostream>
#include <list>
#include "Card.h"

using namespace std;

class Deck {
public:
    Deck();
    virtual ~Deck();
    void reset();
    void shuffle();
    Card getNextCard();
    void printAll();
private:
    Card deck[];
    int nextCard;
};

#endif	/* DECK_H */ 


1
2
3
Deck::Deck() {
  deck = ???
}
closed account (yUq2Nwbp)
if your deck is type of Card then you can change your private member Card deck[] to Card *deck and write

Deck::Deck()
{
deck = new Card[52];
}

.....also you can't write Card deck[]; ....you must initialize it but as your array in class you can't do that...
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#ifndef DECK_H
#define DECK_H

#include <iostream>
#include <list>
#include "Card.h"

class Deck
{
public:
    Deck();
    virtual ~Deck();
    void reset();
    void shuffle();
    Card getNextCard();
    void printAll();
private:
    enum { ENumberOfCards = 52 };
    Card deck[ENumberOfCards];
    int nextCard;
};

#endif	// DECK_H 


Should the destructor be virtual?

As to the card values, that depends on Card.
closed account (yUq2Nwbp)
kbw in this case destructor shouldn't be virtual but it doesn't prevent.......virtual destructor is used when there is inheritance among classes.....
Thanks guys it works!
closed account (yUq2Nwbp)
you are welcome
Topic archived. No new replies allowed.