Originally Posted by
appleGuy
How would I go about this, classes that have classes in it protected section...Can you even do that?
Sure you can. It's called class nesting. One common usage is to create functors that allow a more specialized usage of the STL algorithms:
Code:
/*
A simple class with a string data member and a function that returns its member.
*/
class CItem {
public:
CItem() {};
virtual ~CItem() {};
std::string id() const { return id_; }
private:
std::string id_;
};
/*
CInventory is an array of CItems. In its private section a functor is created
to help delete an element by the id data member of CItem.
*/
class CInventory {
public:
CInventory();
virtual ~CInventory() {};
virtual CInventory& remove(const std::string&);
protected:
std::vector<CItem*> contents_;
private:
class is_ID {
public:
is_ID(const std::string& s): id_(s) {}
bool operator()(const CItem* obj) const { return obj->id() == id_; }
private:
std::string id_;
};
};
/*
This is the definition of CInventory::remove(). In it, the algorithm find_if() is
used with a predicate function. Our functor defined as a private member.
This way it was possible to find elements based on CItem data members.
/*
CInventory& CInventory::remove(const std::string& str) {
std::vector<CItem_Ptr>::iterator iter;
iter = std::find_if(contents_.begin(), contents_.end(), is_ID(str) );
if( iter == contents_.end() ) {
std::cerr << '\n' << "Object is not in inventory." << std::endl;
return *this;
}
// Ok to remove
contents_.erase(iter);
return *this;
}