C++ Polymorphism, incomplete downcasting
-
13-03-2021 - |
質問
I have an array which holds references to a bland base type, let's call it Object
.
I have derived Class1
from Object
and Class2
from Class1
.
#include <vector>
class Object {};
class Class1 : public Object {
public:
virtual std::string ToString() {return "it is 1";}
};
class Class2 : public Class1 {
public:
virtual std::string ToString() {return "it is 2";}
};
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<Object *> myvec;
myvec.push_back(new Class2());
printf("%s", (static_cast<Class1*>(myvec[0]))->ToString().c_str());
return 0;
}
I call ToString()
by casting from Object *
to Class1 *
like so
printf("%s", (static_cast<Class1*>(myvec[0]))->ToString().c_str());
My question is, will this output 1 or 2 when the object is in fact of Class2
but not down cast to that specifically? Is the virtual
keyword having the intended effect?
解決
I slightly misread your question when I first answered, regarding demons and your nostrils.
The virtual
keyword will have it's intended effect. That is, You will see 2. Although you have casted to Class1
, the vtable will work it's magic.
他のヒント
It should call Class2
's virtual function, since the object is of that type.
Remember: the purpose of a virtual function is to call the actual class's function, not the function for the class the pointer/reference currently appears to be.
First, this is not a safe cast. But assuming that myvec[i]
is a pointer the an object you are casting to, then it will call the appropriate method for that class.