#include "boost/smart_ptr.hpp" #include #include #include // If this is true, then the function DisplayAndPlay, takes smart pointers as arguments, otherwise it takes "raw pointers" #define PASS_SMART_PTR 1 using namespace std; #if defined(WIN32) || defined( __NT__) ostream& operator << ( ostream& strm, const string &str) { strm << str.c_str(); return strm; } #endif class MusicProduct { protected: std::string _title; public: MusicProduct( const string& Title) { _title = Title; } const std::string& get_title() const { return _title; } virtual void play() const = 0; virtual void displayTitle() const = 0; virtual ~MusicProduct() = 0; }; MusicProduct::~MusicProduct() { } class Cassette : public MusicProduct { public: Cassette( const string& Title) : MusicProduct( Title) {} virtual void play() const { cout << "Playing " << _title << " in the tape player" << endl; } virtual void displayTitle() const { cout << "Cassette has title = " << _title << endl; } virtual ~Cassette() { cout << "destroying the cassette named " << _title << endl; } }; class CD : public MusicProduct { public: CD( const string& Title) : MusicProduct( Title) {} virtual void play() const { cout << "Playing " << _title << " in the CD player" << endl; } virtual void displayTitle() const { cout << "CD has title = " << _title << endl; } virtual ~CD() { cout << "destroying the CD named " << _title << endl; } }; #if PASS_SMART_PTR void DisplayAndPlay( boost::shared_ptr smarty, int HowMany) { smarty->play(); cout << HowMany << " are in stock" << endl; } int main() { boost::shared_ptr DiscoGold( new Cassette("DiscoGold")); boost::shared_ptr Yani( new CD("Yani's Best")); DisplayAndPlay( DiscoGold, 10); DisplayAndPlay( Yani, 5); DisplayAndPlay( DiscoGold, 10); cout << "starting cleanup" << endl; return 0; } #else void DisplayAndPlay( const MusicProduct* smarty, int HowMany) { smarty->play(); cout << HowMany << " are in stock" << endl; } int main() { boost::shared_ptr DiscoGold( new Cassette("DiscoGold")); boost::shared_ptr Yani( new CD("Yani's Best")); DisplayAndPlay( DiscoGold.get(), 10); DisplayAndPlay( Yani.get(), 5); DisplayAndPlay( DiscoGold.get(), 10); cout << "starting cleanup" << endl; return 0; } #endif