user44322
user44322

Reputation: 361

Calling STL container's built in function

I am programming in C++ and cant figure out how to access the STL container in a parent class. I have the following classes:

class Card
class CardPile : private vector<Card*>
class Deck : public CardPile{Foo()}

I know that if Foo() was in CardPile class I can call vector's size with size(). How would I call vector's size() function from Foo().

EDIT: Unfortunately, I am not allowed to change any of the class definitions

Upvotes: 2

Views: 192

Answers (2)

juanchopanza
juanchopanza

Reputation: 227558

size() is a private method of CardPile, but you could, it if suits the design, make it public or protected:

class CardPile : private std::vector<Card*>
{
 public: // or protected
  using std::vector<Card*>::size;
};

This will allow you to call size() either everywhere (public) or from derived classes (protected).

But bear in mind that standard library containers are not designed to be inherited from, specially publicly. So you could change your CardPile class to hold a std::vector<Card*> data member. And after that, you may look into holding smart pointers in the vector if you are currently dealing with dynamically allocated Card objects.

class CardPile : 
{
 public: // or protected
  std::vector<Card*>::size_type size() const { return cards_.size(); }
 private: 
  std::vector<Card*> cards_
};

Upvotes: 2

Caribou
Caribou

Reputation: 2081

class Card {};

class CardPile : private std::vector<Card*> 
{};

class Deck : public CardPile
{
   public:
   void Foo(){this->size();} //FAIL
};

By privately inheriting you are essentially saying that you want the implementation, but the interface is not what you want to expose. So really you should provide an interface that reflects the object you are modelling.

So unless you publicly inherit (or use juanchopanzas suggestions) to expose all(some) of the vectors interface, you need to provide methods (A Cardpile Interface) that calls the specific vector methods you need. Something like:

class CardPile : private std::vector<Card*> 
{ size_t pileHeight() {return size(); };

There is more discussion of Private / Protected vs Public inheritence here :

Why do we actually need Private or Protected inheritance in C++?

Upvotes: 1

Related Questions