I created a Baseclass vector shared_ptrto store Derivedclass shared_ptrs and run into some problems.
The following simplified example shows what is happening.
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
class Base {
public:
Base(int i) : val(i) {}
int val;
};
class Derived : public Base {
public:
Derived(int i) : Base(i) {}
};
int main()
{
vector<shared_ptr<Base>> vec1{
make_shared<Base>(5),
make_shared<Base>(99),
make_shared<Base>(18)};
for (auto const e : vec1)
cout << e->val << endl;
cout << endl;
vector<shared_ptr<Derived>> vec2{
make_shared<Derived>(5),
make_shared<Derived>(99),
make_shared<Derived>(18)};
for (auto const e : vec2)
cout << e->val << endl;
cout << endl;
vector<shared_ptr<Base>> vec3{
make_shared<Derived>(5),
make_shared<Derived>(99),
make_shared<Derived>(18)};
for (auto const e : vec3)
cout << e->val << endl;
cout << endl;
return 0;
}
When I run this on my machine (Win7 64bit with MS VS2013), I get the following output:
5
99
18
5
99
18
-572662307
99
18
What am I missing here?
Thank.
source
share