Rajeshwar
Rajeshwar

Reputation: 11651

Why does dynamic cast only work with references and pointers

Why does the dynamic cast only work with pointers and references ? Say I have something like this

struct foo
{
    virtual void test(){}
};
struct bar : public foo
{
};

why doesn't something like this work

foo* f = new bar();
bar& b = dynamic_cast<bar>(*f); //Fail must be either pointer or reference

Now suppose bardid have a conversion constrcutor for its parent foo. My question is why does dynamic cast only take in pointers and references and not simple objects like static_cast does ?

Upvotes: 5

Views: 1876

Answers (2)

user6710094
user6710094

Reputation: 77

Dynamic cast works when there is a relationship (inheritance) between two classes base B and derived D. If we use non reference and pointer type it means we are converting them, then we require conversion operator eg. operator B() or operator B() and return what you want.

Here the case is different : we have an object which has two parts 1. base type 2. specific to derived type only. Here when we cast using pointer or reference, it just switches the pointer to correct part and from type we know how much addresses it can move to access the elements(fields).

Upvotes: 2

lubgr
lubgr

Reputation: 38267

dynamic_cast has only one purpose: casting along an inheritance hierarchy, specifically up the hierarchy as well as down the hierarchy. Let's assume it worked for values as in your example, what will happen here:

bar b{};

auto sliced = dynamic_cast<foo>(b);

The object sliced is of type foo, but contains only the foo subobject of b. This is practically never what you want. Handling instances of polymorphic types by value is not a good option, see also this thread.

For the inverse direction, it is even more obvious why this can't really work well:

bar b{};
foo& f = b;

// Pass f by value to dynamic_cast?! Then, the argument is already
// sliced before the dynamic_cast is even able to determine its
// runtime type.
bar downcast = dynamic_cast<bar>(f);

The comment in the last example is a bit exaggerated, as dynamic_cast is an operator and not a function, but it should pinpoint the issue here: conversions across a hierarchy don't play nice with value semantics, and dynamic_cast reflects that.

Upvotes: 4

Related Questions