I am attempting to understand why casting from a base class to an derived class using pointers compiles fine, but casting using non-pointer object produces the error C2440.
Below I have a base class ThreadedMessage that is inherited by class GPSMessage.
struct ThreadedMessage
{
ThreadedMessage()
: m_Type(0), m_ID(0)
{ }
ThreadedMessage(uint Type, uint ID = 0) :
m_Type(Type), m_ID(ID)
{ }
uint m_Type;
uint m_ID;
};
struct GPSMessage : public ThreadedMessage
{
GPSMessage()
: ThreadedMessage()
{ }
GPSMessage(double lat, double lon)
: ThreadedMessage(1), m_lat(lat), m_lon(lon)
{ }
double m_lat;
double m_lon;
};
In myFunction I am attempting to cast from the base class to the derived class.
void myFunction(const ThreadedMessage& msg)
{
const GPSMessage* message = static_cast<const GPSMessage*>(&msg); // Compiles fine
const GPSMessage message1 = static_cast<const GPSMessage>(msg); // Error C2440
}
The call to myFunction() looks like this:
GPSMessage msg(21.123, 12.321);
myFunction(msg);
When I compile, the casting of a pointer compiles fine, but the non-pointer casting fails with the following error:
error C2440: 'static_cast' : cannot convert from 'const ThreadedMessage' to 'const GPSMessage' No constructor could take the source type, or constructor overload resolution was ambiguous
Why am I unable to cast from the base class to the derived class with non-pointer variables?
Compiler is MS VS 2008 C++.
Yes, I have looked at other similar SO questions, but the ones I have read don't seem to answer my question.