samedi 4 avril 2015

dynamic_casting of objects confusion

The book The c++ programming language has sections about dynamic_cast that I'm not sure I understand correctly.


The purpose of dynamic_cast is to deal with the case in which the correctness of the conversion cannot be determined by the compiler. In that case, dynamic_cast(p) looks at the object pointed to by p (if any). If that object is of class T or has a unique base class of type T, then dynamic_cast returns a pointer of type T* to that object; otherwise, nullptr is returned. If the value of p is nullptr, dynamic_cast(p) returns nullptr. Note the requirement that the conversion must be to a uniquely identified object. It is possible to construct examples where the conversion fails and nullptr is returned because the object pointed to by p has more than one subobject representing bases of type T.

Does "It is possible to construct examples where the conversion fails and nullptr is returned because the object pointed to by p has more than one subobject representing bases of type T" mean something like this?



class a {
public:
a() { }
};

class b : public a {
public:
b() { }
};

class z : public a, public b {
public:
z() { }
};

void f(z* p) {
a* x = dynamic_cast<a*>(p); // ambiguous
}


And another one, this is taken from the book:



class Component : public virtual Storable { /* ... */ };
class Receiver : public Component { /* ... */ };
class Transmitter : public Component { /* ... */ };
class Radio : public Receiver, public Transmitter { /* ... */ };


The ambiguity for a pointer to a Radio object is not in general detectable at compile time. This kind of run-time ambiguity detection is needed only for virtual bases. For ordinary bases, there is always a unique subobject of a given cast (or none) when downcasting (that is, toward a derived class; §22.2). The equivalent ambiguity for virtual bases occurs when upcasting (that is, toward a base), but such ambiguities are caught at compile time.

I totally don't understand this. What does this mean "For ordinary bases, there is always a unique subobject of a given cast"? I just caused an ambiguity error with my above example. And "The equivalent ambiguity for virtual bases occurs when upcasting", what does that mean? Can virtual bases be ambiguous? Can anyone explain this clearer?


Aucun commentaire:

Enregistrer un commentaire