Home > Mobile >  Advice for getting a pointer to an object from a vector stored inside a class
Advice for getting a pointer to an object from a vector stored inside a class

Time:06-28

class Element {
    class Point {
        private:
            double x;
            double y;
        public:
            //getters/setters for x and y
    };
    private:
        std::string name;
        std::vector<Point> values;
    public:
        void insertValue(unsigned int index, double x, double y);
        ...
};

class Collection {
    private:
        std::string name;
        std::vector<Element> elements;
    public:
        ...
        ...
        Element* elementAt(unsigned int index) const {
            return const_cast<Element*>(&elements.at(index));
        }
};

What I need is to get an Element in a certain index from the collection to do operations like Element::insertValues. It is a bad practice doing it as it's done in the Collection::elementAt method (using const_cast)? Is it better to remove the const qualifier from the method? I marked the method const since the method itself does not modify the object.

CodePudding user response:

The usual idiom for this is to have two methods, a const one and a non-const one. In this case one returns a const Element *, and the other one returns an Element *, keeping everything const-correct.

        const Element* elementAt(unsigned int index) const {
            return &elements.at(index);
        }

        Element* elementAt(unsigned int index)  {
            return &elements.at(index);
        }

Yes, it is true that this leads to some code duplication. Such is life, noone has ever accused C of being compact and concise.

P.S.: you didn't ask this, but an even better idiom would be to return a reference, rather than a pointer. std::vector::at returns a reference, why shouldn't your pinch-hitter do the same?

  • Related