Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

stl vector of non-homogeneous derived class objects

Hi

I need to fill a stl vector with different derived class objects(non-homogeneous).Thats
what I want to acheive with my implementation. Hence I'm using
polymorphism so that I can create a vector of base class pointers and
then use that vector to create new objects of derived classes.
Please let me know if there are any issues with my implementation.

//base class
class container {
virtual ~container(){ };
virtual Operator() = 0; //this is overridden in derived classes
}

//derived class
template <typename T> class product : public sv_pipeOps {

public:
product(Matrix<T>& a, Matrix<T>& b, Matrix<T>& c)
{
//implementation
}

//virtual function Operator overridden here
void Operator()
{
//implementation
}

};

//derived class
template <typename T> class equals : public container {

public:
equals(Matrix<T>& a, Matrix<T>& b)
{
//implementation
}

//virtual function Operator overridden here
void Operator()
{
//implementation
}

};

template <typename T> class Matrix
{
~Matrix(){
delete x;
for (int i=0; i<container_bptr.size(); ++i) delete container_bptr[i];

Matrix<T>& operator*( Matrix<T> & rhs)
{
Matrix<T> *c = new Matrix<T>;
container_bptr.push_back( new product<T>(*this,b,*c); //creates product class object
return *c;
}

Matrix<T>& operator=( Matrix<T> & rhs)
{
container_bptr.push_back( new equals<T>(*this, rhs); //creates equals class object
return *this;
}

protected:
std::vector< container* > container_bptr;

};

regards
kiran
[1860 byte] By [mpakala] at [2007-11-11 10:10:12]
# 1 Re: stl vector of non-homogeneous derived class objects
Heterogeneous containers is a topic I've discussed several times in the past. The common approaches nowadays are using a smart pointer that wraps a polymorphic object or using a reference wrapper. There's absolutely no need to reinvent the wheel writing new container classes and besides, containers shouldn't be polymorphic. Here are two different articles that discuss these techniques:
http://www.dev-archive.com/cplus/10MinuteSolution/28347
http://www.dev-archive.com/cplus/10%20Minute%20Solution/32792/0
Danny at 2007-11-11 20:59:25 >