I made following 3 classes:
struct Parent1
{
virtual void f()
{
cout << "\nParent1::f";
}
};
struct Parent2
{
virtual void g()
{
cout << "\nParent2::g";
}
virtual void z()
{
cout << "\nParent2::z";
}
};
struct Child : public Parent1, public Parent2
{
virtual void h()
{
cout << "\nChild::h";
}
};
In main, when I call function z
of Parent2
, it instead calls function h
of the child class. Why is it happening so?
Following is the main
function:
int main()
{
Child obj;
Parent2 * p2 = (Parent2*)(Parent1*)&obj;
p2->z();
return 0;
}
The first explicit conversion from &obj
i.e. Child*
to Parent1*
is an upcast. The result will point to the base class sub-object. The next explicit conversion is from Parent1*
to Parent2*
. Since these classes are not directly related, this is a reinterpretation cast. But the types are not pointer-interconvertible, so when you call the function through the reinterpreted pointer, the behaviour of the program is undefined.
You should avoid using C-style casts to prevent mistakes like this. In this case, no explicit cast is needed at all. This works correctly:
Parent2 * p2 = &obj;
And never reinterpret pointers unless you know what it means and that it is OK to do so.