Question

I have the following classes and methods:

//Base class
class Node {
    public:
        virtual ~Node() {};
        Node() {};
    private:
        // Private things for my implementation.
};

class Element : public Node {
    public:
        // Returns the name of the element.
        const xml::String &name() const {
            return eleName;
        }

        static bool is_Element(const Node *base) {
            Element *p = NULL;
            p = dynamic_cast<Element*>(base);
            return (p!=NULL);
        }

        static const Element *to_Element(const Node *base) {
            return dynamic_cast<Element*>(base);   
        }

    private:
        s_namespace eleNamespace;
        xml::String &eleName;
        // Private things for my implementation.
};

Here when I dynamic cast it says the following compile error. How to correct it? One method is to simple remove the const of the parameters. But I donot think that is the correct method.

oops.cpp: In static member function ‘static bool xml::Element::is_Element(const xml::Node*)’: oops.cpp:208:44: error: cannot dynamic_cast ‘base’ (of type ‘const class xml::Node*’) to type ‘class xml::Element*’ (conversion casts away constness) oops.cpp: In static member function ‘static const xml::Element* xml::Element::to_Element(const xml::Node*)’: oops.cpp:213:47: error: cannot dynamic_cast ‘base’ (of type ‘const class xml::Node*’) to type ‘class xml::Element*’ (conversion casts away constness)

Was it helpful?

Solution

Use dynamic_cast<const Element*> instead.

You can also make your class const-correct, by implementing two different functions for a const-Argument and a non-const Argument:

    static const Element *to_Element(const Node *base) {
        return dynamic_cast<const Element*>(base);   
    }

    static Element *to_Element(Node *base) {
        return dynamic_cast<Element*>(base);   
    }

So if the caller has a non-const Node he probably also wants a non-const Element and now he can get it...

OTHER TIPS

Try this:

static bool is_Element(const Node *base) {
    const Element *p = NULL; // Add a const keyword here
    p = dynamic_cast<const Element*>(base); // Add a const keyword here
    return (base!=NULL);
}

And the same for to_Element

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