Search code examples
c++xalanstatic-cast

Why can't I use a static_cast from one Xalan class to its base class?


Why does the compiler (g++) complain about this line of code?

    XalanNode *docElement = static_cast<XalanNode*> (docBuilder_->getDocument()->getDocumentElement());

The error I get from the compiler is:

 error: invalid static_cast from type `amxalanc_1_6::XalanElement*' to type `amxalanc_1_6::XalanNode*' 

Without the static_cast, the compiler prints:

error: cannot convert `amxalanc_1_6::XalanElement*' to `amxalanc_1_6::XalanNode*' in initialization 

The XalanElement class is defined as:

class XALAN_DOM_EXPORT XalanElement : public XalanNode

The documentation also shows that XalanNode should derive from XalanElement, as you can see here - XalanElement Class Reference.

Within XalanDocument.hpp, the method signature of getDocumentElement() is:

virtual XalanElement* getDocumentElement() const = 0;

Solution

  • Most of the Xalan headers only use forward declarations for classes that they are not defining even if they are declaring functions that take or return pointers to these classes. (This is common and good practice.)

    For your compiler to see the fact that XalanElement is derived from XalanNode you need to explicitly #include the header which defines XalanElement.