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.
The usual idiom for this is to have two methods, a
constone and a non-constone. In this case one returns aconst Element *, and the other one returns anElement *, keeping everything const-correct.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::atreturns a reference, why shouldn't your pinch-hitter do the same?