I have been working on a blackjack game and have tried to make use of the inheritance feature of classes in my design, but I am not sure whether I have implemented them correctly....
I have a player class and a dealer class which is derived from the player class (ie for functions such as Status and CheckHand)
This runs fine but as it stands there is nothing to stop a dealer object calling a function from the player class which it has inherited but which is only intended for a player object (ie it accesses a private member of the player class)
eg.
Player class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Player
{
public:
Player(string PlayerName);
float CountStack() const;
constint CheckHand() const;
int PlaceBet(constfloat NewBet);
void Status() const;
private:
float Bet;
protected:
vector<Card> Hand;
int HandValue;
};
Dealer class:
1 2 3 4 5 6 7 8 9
class Dealer: public Player
{
public:
void Shuffle();
const Card Deal();
private:
Card Shoe[209];
};
With this setup I could potentially do something like this:
Dealer.PlaceBet(20);
which would create an error.
I did think of putting functions such as PlaceBet as private within the class but then I can't use them within my main.cpp file.
Is there a way of being able to use class functions in my main.cpp file without leaving potential errors open as above?
You can actually adjust method access under inheritance.
1 2 3 4 5 6 7 8 9 10
class Dealer: public Player
{
public:
void Shuffle();
const Card Deal();
private:
Card Shoe[209];
using Player::PlaceBet; // inherits PlaceBet privately in Dealer
};
To make this clear you want to be able to use some function through Player objects but not through Dealer objects?
I think this can be dealt if you think about what public inheritance means: Dealer is a Player. So it should use all players functions. If it does not maybe it shouldn't be a Player (use different strategy). You can probably make both inherit from a common base class.
In special cases techniques like this the one mentioned by @IceThatJaw can be applied
Yes I did wonder about having another class which both dealer and player could be derived from but thought it might get a bit bloated.
As a follow up question, is there no way of using the protected section to achieve what I am after - so that I can control which functions are inherited but can still use them in my main.cpp file?