Can I create an STL vector of an abstract class (C++)?

ElDonAntonio

Senior member
Aug 4, 2001
967
0
0
I thought it posed no problem, but it doesn't seem to work for me. I have an abstract class (t3Object) with a pure virtual function, and one (for the moment) derived class from it. I wrote all the code for the virtual function in the derived class, no problem.

I create a vector of the base abstract class, and the compiler complains of the following:

\visual studio\vc98\include\stl\stl_vector.h(639) : error C2259: 't3Object' : cannot instantiate abstract class due to following members:
t3object.h(5) : see declaration of 't3Object'

\visual studio\vc98\include\stl\stl_alloc.h(195) : while compiling class-template member function 'void __thiscall std::vector<class t3Object,class std::__default_alloc_template<1,0> >::_M_insert_aux(class t3Object *,const class t3Object &)'


Anyone has an idea how to solve this?
 

singh

Golden Member
Jul 5, 2001
1,449
0
0
Since you can't instantiate an abstract class, how do you expect to create a vector from it? And why?
 

ElDonAntonio

Senior member
Aug 4, 2001
967
0
0
Well suppose I want a vector containing various "objects" (an object being the base class). Among the objects, I could have cubes, spheres, etc.
I don't want to have to create different vectors for all differents objects, I'd like one vector that could contain spheres, cubes, etc (all derived from the base class object).

I KNOW this is possible, as I already did it before, but I just can't seem to find my bug here...
 

singh

Golden Member
Jul 5, 2001
1,449
0
0
Nope, you can't do it. At least in my understanding, you can't do it. It doesn't make sense. In order to insert something into a vector, the template has to first instantiate the class. Since this is not possible with an abstract class, you can't do it!

A better place to ask this question might be in comp.lang.c++.moderated.
 

ElDonAntonio

Senior member
Aug 4, 2001
967
0
0
ok, suppose then I change the pure virtual function to a virtual function (the class can be instantiated then, right?), and that I put some bogus code in the body of the virtual function (which will never be called anyways if I code the equivalent functions of the derived classes), do you think that will that work?
 

singh

Golden Member
Jul 5, 2001
1,449
0
0
Doing that would remove the "abstract" part of the class, so it would solve your problem.