Question

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 ?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top