Skip to main content

Posts

Showing posts from July, 2013

A STL vector usage through shared_ptr

We know vector can store homogeneous kind of stuff. That is, it can store type int, string etc individually but not element of type int with string etc. However, sometimes we might have requirements that it can store elements which are in inheritance relation and can do stuff by calling function of respective element stored in vector. As an example, I've a Shape class from which I've derived Circle, Polygon etc. Now I want to store Circle, Polygon object in a vector and then access each element by its iterator and draw shape accordingly. C++ 2011 made it possible via shared_ptr. Thanks to Stephan aka STL. Code snippet #include < iostream > #include < memory > #include < vector > using namespace std; class Shape { public:     Shape(){}     virtual ~Shape(){}     virtual void draw(int x, int y)     {         cout << "Shape::draw(" << x << ", " << y << ")" << endl;     } private:     Shape(const Sh