I am the following structure. I minimized to the shortest possible way to reproduce the error:
I have two level of derived class. I don't have any compilation error. The error is at the runtime:
Unhandled exception at 0x00007FFF1021CF19 in base.exe: Microsoft C++ exception: std::__non_rtti_object at memory location 0x00000022B9BDF458.
Is there any suggection?
#include <iostream>
#include <vector>
#include <memory>
class Base {
public:
int a;
Base(int _a) : a(_a) {};
virtual void print() = 0;
};
class derivedA : public Base
{
public:
derivedA(int _a) : Base(_a) {};
void print() { std::cout << "dA" << std::endl; }
};
class derivedB : public derivedA
{
public:
derivedB(int _a) : derivedA(_a) {};
void print() { std::cout << "dB" << std::endl; }
};
void construct(std::vector<derivedA*>& da_vec) {
da_vec.push_back(std::unique_ptr<derivedA>(new derivedB(4)).get());
}
void func(derivedA& da)
{
derivedB& db = dynamic_cast<derivedB&>(da);
db.print();
}
int main()
{
std::vector<derivedA*> da_vec;
construct(da_vec);
for (auto& da : da_vec)
func(*da);
}