user3191398 user3191398 - 4 months ago 12
C++ Question

Transform std:vector<reference_wrapper<Base>> to std:vector<reference_wrapper<Derived>> Runtime error time: 0 memory: 3412 signal:6

I am trying to convert vector of references to Base objects to vector of references to Derived objects. Everything is compiling fine, but i got this error: Runtime error time: 0 memory: 3412 signal:6

This is my code:

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

struct B {
B(int i) { b = i; }
virtual ~B() {}
int b;
};

struct D: public B {
D(int i): B(i) {}
};

typedef vector<reference_wrapper<B>> refB;
typedef vector<reference_wrapper<D>> refD;

void dynamicCast(refB &b, refD &d)
{
for(const auto& bb: b)
{
d.push_back(dynamic_cast<D&> (bb.get()));
}
}

int main() {
vector<B*> numbers;
refB refNumbers;
refD dNumbers;

for(int i = 0; i < 10; i++)
{
numbers.push_back(new B(2*i));
refNumbers.push_back(*numbers[i]);
}

dynamicCast(refNumbers, dNumbers);

return 0;
}


What is wrong with dynamicCast() function?

Answer

Nothing is wrong with dynamicCast(). The problem is here:

    numbers.push_back(new B(2*i));

You only ever construct instances of B which is the base class. You can't possibly cast them to D which is the derived class.

Perhaps you meant to construct derived instances and store them in your vector of references to base.