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
virtualkeyword will have it’s intended effect. That is, You will see 2. Although you have casted toClass1, the vtable will work it’s magic.