Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading