Re: STL vector Problem: push_back derived object but get base object
On Mar 11, 10:40 am, gph <gpen...@gmail.com> wrote:
Hello, I have a problem about STL vector. I expect vector can hold my
derived objects. But it doesn't. My program is like this:
....
main(){
vector<CBase> v;
CDerived d;
v.push_back(d);
The explanation is that the vector is declared to actually hold CBase
obejcts.
It does *not* hold polymorphic references to them. To simplify what's
happening
consider a case without the vector:
CBase c;
CDerived d;
c = d;
This is called "slicing", as it only copies the base part of d into c,
since
that's all that c can hold.
What you probably want is the vector to hold pointers to CBase, and
then have
it hold dynamically allocated objects of the derived type. THat is,
they should
be created with "new".
However, this is very error-prone in terms of memory management, and
will likely
leak unless you use a "smart pointer", to hold your raw pointers. The
easiest
way to do this safely is to use the boost::shared_ptr class:
#include "boost/shared_ptr.hpp"
#include <vector>
#include <iostream>
class CBase {
public:
virtual void print(){ std::cout << "Base\n" << std::endl;}
};
class CDerived : public CBase {
public:
void print(){ std::cout << "Derived\n" << std::endl;}
};
typedef boost::shared_ptr<CBase> CBase_shptr;
typedef std::vector<CBase_shptr> CBase_vector;
int main()
{
CBase_vector v;
v.push_back(CBase_shptr(new CDerived));
CBase_vector::iterator i;
for(i = v.begin(); i != v.end(); ++i) {
(*i)->print();
}
}
--
Chris
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]