Multiple inheritance and casting

A subclass that inherits from two different reference-counted objects inherits a single x::obj superclass, since it's virtually inherited:

class widgetObj : virtual public x::obj {

// ....

};

class containerObj : virtual public x::obj {

// ....

};

class boxObj : public widgetObj, public containerObj {

// ....
};

typedef x::ref<widgetObj> widget;
typedef x::ref<containerObj> container;
typedef x::ref<boxObj> box;

typedef x::ptr<widgetObj> widgetptr;
typedef x::ptr<containerObj> containerptr;
typedef x::ptr<boxObj> boxptr;

This is the reason why x::obj should always be inherited virtually.

An x::ref or an x::ptr to a subclass may be converted to an x::ref or an x::ptr to its superclass. The opposite is also true: an x::ref or an x::ptr to a superclass may be converted to an x::ref or an x::ptr to a subclass, but only if the referenced object is actually an instance of the subclass, of course:

widget wRef;
container cRef;

// ...

cRef=wRef;

// ...

wRef=cRef;

A runtime exception gets thrown if the pointer or the reference cannot be converted. Use dynamic_cast<> if it's unknown whether the superclass reference refers to an instance of a subclass:

if (!wRef.null())
{
    widgetObj *wptr(&*wRef);

    if (dynamic_cast<boxObj *>(wptr))
    {
       container cRef(wRef);

       // ....
    }
}