0

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)

footy
  • 5,803
  • 13
  • 48
  • 96

2 Answers2

8

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...

  • This is exactly what I wanted achieve! You read my mind. Thanks :) – footy Mar 03 '13 at 16:37
  • Trying to understand here: In the solution above, is function to_Element() overloaded ? But I had read functions don't become overloaded just by making arguments const in one and non-const in other. How does this particular soln. work? – goldenmean Mar 06 '13 at 16:07
2

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

masoud
  • 55,379
  • 16
  • 141
  • 208