Suppose I have a base class and 2 classed derived from that. All the derived classes has its own logic that incompatible between them. The test application is as following:
#include <iostream>
#include <vector>
class Base
{
public:
Base(int x) { m_x = x; }
virtual int getResult() { return m_x; }
protected:
int m_x;
};
class DerivedA : public Base
{
public:
DerivedA(int x) : Base(x) {}
int getResult() override { return m_x * 2; }
};
class DerivedB : public Base
{
public:
DerivedB(int x) : Base(x) {}
int getResult() override { return m_x * m_x; }
};
int main()
{
std::vector<Base *> objects;
objects.push_back(new DerivedA(1));
objects.push_back(new DerivedB(2));
objects.push_back(new DerivedA(3));
objects.push_back(new DerivedB(4));
for(Base *object: objects)
{
DerivedA *obj = static_cast<DerivedA *>(object);
if(obj != nullptr)
{
std::cout << obj->getResult() << std::endl;
}
}
return 0;
}
I expect to get only 2 result i.e. that only instances of type DerivedA
can be casted to DerivedA
but not DerivedB
. But to my surprise this is not the case. static_cast
casts DerivedB
to DerivedA
without problem. Why is this happening? I can understand that if I would cast to Base
but not that. At the same time dynamic_cast
works as expected, i.e. casting DerivedB
to DerivedA
fails.
Aucun commentaire:
Enregistrer un commentaire