Constructor Not Initializing Passed Values

Hello all,

Long time reader, first time poster. I'm trying to create a black jack simulator with C++. I am creating a deck of cards where each card is a Card object with a rank and suit variable, and enums RANK and SUIT respectively. I'm using a member initializer list for default values, which works fine, but if I try to use the constructor to create a Card object with different values it still uses the default values.

What am I missing in order to initialize a Card object with new values?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Card class struct
class Card
{
public:
	enum RANK{ ACE = 1, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING}; // RANK variables can only hold the values enumerated here.
	enum SUIT{ CLUBS, DIAMONDS, HEARTS, SPADES }; // SUIT variables can only hold the values enumerated here.

 Card( RANK rank = ACE, SUIT suit = SPADES, bool isFaceUp = true );
};

// Card ctor
Card::Card( RANK rank, SUIT suit, bool isFaceUp ) : rank ( ACE ), suit (SPADES), isFaceUp (true) {}

// In main

Card cObj1; // Returns rank of ACE
Card cObj2( Card::KING, Card::SPADES, true ); // Returns rank of ACE

cObj2.rank = Card::KING; // Returns rank of KING 
Presumably you have members of Card named rank, suit and isFaceUp although they aren't present in your snippet.

I'm using a member initializer list for default values, which works fine, but if I try to use the constructor to create a Card object with different values it still uses the default values.

You want to use the member initializer list for the actual values. The default values are supplied by the compiler when you use the constructor with fewer arguments than the constructor requires as indicated by the declaration.

1
2
// Card ctor
Card::Card( RANK rank, SUIT suit, bool isFaceUp ) : rank (rank), suit (suit), isFaceUp(isFaceUp) {}


Naming the parameters/members differently might improve readability.
That sounded like good reasoning and I implemented the change to:

Card::Card( RANK rank, SUIT suit, bool isFaceUp ) : rank ( rank ), suit ( suit ), isFaceUp ( isFaceUp ) {}

But I'm still not able to do something like:
Card cObj( Card::KING, Card::DIAMONDS, true );
And have it set cObj.rank to KING, it still sets it to ACE initially though it compiles without issue.
This is where providing a compilable code sample rather than an arbitrary snippet with no context proves helpful, because it works just fine for me if I mock it up.

http://ideone.com/Oe2tit
Topic archived. No new replies allowed.