Why can't we declare a std::vector<AbstractClass>?
abstract-class, c++, stl
Solution
You can't instantiate abstract classes, thus a vector of abstract classes can't work.
You can however use a vector of pointers to abstract classes:
std::vector<IFunnyInterface*> ifVec;
This also allows you to actually use polymorphic behaviour - even if the class wasn't abstract, storing by value would lead to the problem of object slicing.
Problem
Having spent quite some time developping in C#, I noticed that if you declare an abstract class for the purpose of using it as an interface you cannot instantiate a vector of this abstract class to store instances of the 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 the vector of abstract class causes this error in MS VS2005: ``` error C2259: 'IFunnyInterface' : cannot instantiate abstract class ``` I see an obvious workaround, which is to replace IFunnyInterface with the following: ``` class IFunnyInterface { public: virtual void IamFunny() { throw new std::exception("not implemented"); } }; ``` Is this an acceptable workaround C++ wise ? If not, is there any third party library like boost which could help me to get around this ? Thank you for reading this ! Anthony