Question

I have a doubt about downcasting an object in C++.

Here it comes an example:

class A { }
class B : public A { 
  public:
    void SetVal(int i) { _v = i; }
  private:
    int _v;
}

A* a = new A();
B* b = dynamic_cast<B*>(a);
b->SetVal(2);

What would it happen with this example? We are modifying a base clase like if it is a child one... how does it work related with the memory?

With this cast... Is it like creating an instance of B and copying the values of A?

Thanks

Was it helpful?

Solution

A* a;

This just gives you a pointer to an A. It doesn't point anywhere in particular. It doesn't point at an A or B object at all. Whether your code works or not depends on the dynamic type of the object it is pointing at.

So there are two situations you might want to know about. First, this one:

A* a = new A();
B* b = dynamic_cast<B*>(a);
b->SetVal(2);

This will give you undefined behaviour because the dynamic_cast will return a null pointer. It returns a null pointer when the dynamic type of the object is really not a B. In this case, the object is an A. You then attempt to dereference the null pointer with b->SetVal(2), so you get undefined behaviour.

A* a = new B();
B* b = dynamic_cast<B*>(a);
b->SetVal(2);

This will work fine because the object really is a B object. The dynamic cast will succeed and the SetVal call will work just fine.

However, note that for this to work, A must be a polymorphic type. For that to be true, it must have at least one virtual member function.

OTHER TIPS

That shouldn't even compile, because the classes aren't polymorphic so you can't use dynamic_cast.

If it did, it would be undefined behavior.

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