Hi!
I'm writing a program with a base class and multiple derived classes which are stored in a vector. I think it's easiest if I just post a barebones version to demonstrate my problem:
#include <iostream>
#include <vector>
using namespace std;
class Base
{
public:
Base(){};
virtual void identify() const
{
cout << "Base" << endl;
}
};
class Derived1 : public Base
{
public:
Derived1(){};
void identify() const
{
cout << "Derived1" << endl;
}
};
class Derived2 : public Base
{
public:
Derived2(){};
void identify() const
{
cout << "Derived2" << endl;
}
};
int main()
{
//Static
vector <Base> vec;
vec.push_back(Derived1());
vec.push_back(Derived2());
vec[0].identify();
vec[1].identify();
//Dynamic
vector <Base *> vecdyn;
vecdyn.push_back(new Derived1());
vecdyn.push_back(new Derived2());
vecdyn[0]->identify();
vecdyn[1]->identify();
while (!vecdyn.empty())
{
Base *element = vecdyn.back();
vecdyn.pop_back();
delete element;
}
cin.get();
return 0;
}
Running the above program gives me this result:
Base
Base
Derived1
Derived2
...so the Derived1 and Derived2 objects stored in the static vector identify themselves as Base objects while the ones stored in the dynamic vector identify themselves as their respective derive classes. Why are they doing this, and is there a way to make the static objects identify themselves as derived classes rather than base ones?
Much appreciated