Sunday, February 17, 2013

[c/c++] c++ Vector of Abstract Class type



http://www.cplusplus.com/forum/general/17754/


#include <iostream>
#include <vector>
using namespace std;

// abstract base class
class Animal
{
public:
    // pure virtual method
    virtual void speak() = 0;
    // virtual destructor
    virtual ~Animal() {}
};

// derived class
class Dog : public Animal
{
public:
    // polymorphic implementation of speak
    virtual void speak() { cout << "Ruff!"; }
};

int main( int argc, char* args[] )

    // container of base class pointers
    vector<Animal*> barn;

    // dynamically allocate an Animal instance and add it to the container. Note: new returns a pointer
    barn.push_back( new Dog() ); 

    // invoke the speak method of the first Animal in the container
    barn.front()->speak();

    // free the allocated memory
    for( vector<Animal*>::iterator i = barn.begin(); i != barn.end(); ++i )
    {
        delete *i;
    }
    // empty the container
    barn.clear();

    return 0;
}

No comments:

Post a Comment