سؤال

say I have the following class types

class base
{

};

class der : public base
{
};

With static_Cast you can use objects and pointers.

I tried the following - which works (pointers)

base* b = new base();
der * m = static_cast<der*>(b);

However the following does not work

base b;
der m = static_cast<der>(b);

Any suggestions why the second does not work ? Doesn't static cast deal with pointers and objects ? It works with pointers but it doesnt work with the object ?

هل كانت مفيدة؟

المحلول

In the first one, you are saying "I have a pointer, and I promise it's pointing at a der, so please just go with it".1

In the second one, you can make no such promise, because you unambiguously have a base, not a der.


1. Of course, because it doesn't actually point at a der, you'll get undefined behaviour at runtime.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top