Error: Member Unavailable

I have two classes:

class Hand { public: int getTotal(); std::vector<Card>& getCards(); void add(Card& card); void clear(); private: std::vector<Card> cards; }; class Deck : public Hand { public: void rePopulate(); void shuffle(); void deal(Hand& hand); }; 

If the shuffle() function is declared as follows:

 void Deck::shuffle() { std::random_shuffle(cards.begin(), cards.end()); } 

However, this returns the following error:

 'Hand::cards' : cannot access private member declared in class 'Hand' 

Should I just include a function like std::vector<Card>& getCards() , or is there another way to avoid the error.

+4
source share
3 answers

You can declare cards as protected :

 class Hand { public: int getTotal(); std::vector<Card>& getCards(); void add(Card& card); void clear(); protected: std::vector<Card> cards; }; class Deck : public Hand { public: void rePopulate(); void shuffle(); void deal(Hand& hand); }; 
+2
source

Since your Deck class inherits by hand (and it is not a friend class or the Deck::shuffle() method), you can simply make cards protected instead of private . This provides encapsulation, but the method is available for all derived classes.

Just look, among other links and guides:

0
source

In case of inheritance (your case), the best solution is to protect cards :

 protected: std::vector<Card> cards; 

But overall you can make them friends.

 class Hand { friend class Deck; public: int getTotal(); std::vector<Card>& getCards(); void add(Card& card); void clear(); private: std::vector<Card> cards; }; 
0
source

Source: https://habr.com/ru/post/1493793/


All Articles