c++ - Why can't we declare a std::vector<AbstractClass>? -


having spent quite time developping in c#, noticed if declare abstract class purpose of using interface cannot instantiate vector of abstract class store instances of children classes.

#pragma once #include <iostream> #include <vector>  using namespace std;  class ifunnyinterface { public:     virtual void iamfunny()  = 0; };  class funnyimpl: ifunnyinterface { public:     virtual void iamfunny()     {         cout << "<insert joke here>";     } };  class funnycontainer { private:     std::vector <ifunnyinterface> funnyitems; }; 

the line declaring vector of abstract class causes error in ms vs2005:

error c2259: 'ifunnyinterface' : cannot instantiate abstract class 

i see obvious workaround, replace ifunnyinterface following:

class ifunnyinterface { public:     virtual void iamfunny()     {         throw new std::exception("not implemented");     } }; 

is acceptable workaround c++ wise ? if not, there third party library boost me around ?

thank reading !

anthony

you can't instantiate abstract classes, vector of abstract classes can't work.

you can use vector of pointers abstract classes:

std::vector<ifunnyinterface*> ifvec; 

this allows use polymorphic behaviour - if class wasn't abstract, storing value lead problem of object slicing.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -