I have inherited a project from VC++ 6.0 and am trying to bring it into .NET. I am having a problem with the compiler returning the following error in an operator overload:
error C2240: 'static_cast' cannot convert from 'const CObject*' to 'CSomeObject2*'
Where CObject is actually the base class CObject and CSomeObject2 is another class. I was hoping someone might be able to understand how the following code should work as I cannot see how it ever worked, but this is probably due to my misunderstanding.
void CSomeObject2::operator =(const CSomeObject1& baseSrc) // Line 1
{ // Line 2
CSomeObject2& src = *STATIC_DOWNCAST(CSomeObject2, &baseSrc); // Line 3
CSomeObject1::operator =(src); // Line 4
property = src.property; // Line 5
}
Also, CSomeObject2 is derived from CSomeObject1 and CSomeObject1 is derived from CObject. My problem lies on Line 3. I basically agree with the compiler; however, I don't see how this code ever worked. I know it worked in VC++ 6.0, but how? Could someone please explain. Thanks.
Are you sure you "translated" the code correctly? The code piece makes little sense.
Also, what the hell is STATIC_DOWNCAST supposed to be? Not only does it seem to perform an upcast, but the error message does not fit the code. In any case, dynamic_cast is the correct operator to use here.
Besides, this function will only work correctly if the passed object is actually of type CSomeObject2.
So the parameter should have been a reference to CSomeObject2 in the first place.
STATIC_DOWNCAST performs a similar function to DYNAMIC_DOWNCAST; however, the STATIC version will result in an ASSERT when debugging if the result is invalid. Also, the code was translated correctly as I double checked before I submitted it, but thank you for ensuring that was the case. Any more explanations would be greatly appreciated.
STATIC_DOWNCAST and DYNAMIC_DOWNCAST exist in MFC because the compiler didn't support it when MFC needed it, so they rolled their own using a feature built into CObject (IsKindOf).
The world has changed. Even Microsoft have implemented static_cast and dynamic_cast. It's a good idea to use those and ditch the macros unless for some specific reason you don't want to enable RTTI.
I think I may not have stated my question propertly, but the problem that I was having was the const CSomeObject1 being passed by reference and then it's downcasting in Line 3. Why would you ever pass a const object and then try and modify it in the function, I don't see how this ever worked. Maybe I'm looking to explain the unexplainable, lol. Thanks for the replies so far.