Unable to create class vector containing ptr_vector <an_abstract_class>
I need to have std::vector
of boost::ptr_vector
s. To make it easier to manage, I included boost :: ptr_vector in class ( Zoo
) and made a std :: vector ( allZoos
) out of it. Look at the minimal code to reproduce this:
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/utility.hpp>
class Animal
{
public:
virtual char type() = 0;
};
class Cat : public Animal
{
public:
char type() { return 1; }
};
class Zoo
{
public:
boost::ptr_vector<Animal> animals;
};
int main()
{
std::vector<Zoo> allZoos;
Zoo ourCityZoo;
ourCityZoo.animals.push_back(new Cat());
//Uncommenting any of the lines below causes error:
//allZoos.push_back(ourCityZoo);
//allZoos.clear();
return 0;
}
The declaration allZoos
is fine, but calling any of its member functions throws a compiler error: (Full error log was so long, was not posted)
C2259: 'Animal' : cannot instantiate abstract class c:\boost_1_49_0\boost\ptr_container\clone_allocator.hpp 34 1
This had nothing to do with promoting noncopyable utility and UDFs new_clone
, and I tried them with no luck. How can this be solved?
(I am using VS2010)
source to share
In fact, reading to where the error appears would help. He stated clearly and clearly in the Boost source:
template< class T >
inline T* new_clone( const T& r )
{
//
// @remark: if you get a compile-error here,
// it is most likely because you did not
// define new_clone( const T& ) in the namespace
// of T.
//
T* res = new T( r );
BOOST_ASSERT( typeid(r) == typeid(*res) &&
"Default new_clone() sliced object!" );
return res;
}
If you don't specify a way to clone the type, it will try to do it by simply copying it, which is not possible with abstract classes. Add the appropriate method clone
to the function abstract_class
and a new_clone
in your namespace and you should be fine.
Here's a fixed version of your code.
source to share