Reputation: 23
How would I be able to access x or y variables from the octagons vector after storing the object.
I know how I'd access x and y from the lots_of_coordinates vector as this would just be lots_of_coordinates[0].x
but I would want to do the same but from the octagons vector.
public:
int x, y;
};
class OctagonBase {
public:
vector<Coordinate>coordinates;
Coordinate point1;
};
class Octagon : public OctagonBase {
public:
void Coordinates() {
point1.x = 30;
point1.y = 40;
coordinates.push_back(point1);
cout << coordinates[0].x;
}
};
int main() {
vector<Octagon*>octagons;
Octagon o;
o.Coordinates();
octagons.push_back(o);
//how do I access x from octagons?
}
edit:
I've got it to work using octagons[0].point1.x;
and also changing vector<Octagon*>octagons
to vector<Octagon>octagons
. However is there a way to do it with vector<Octagon*>octagons
.
Also if I change int x and y to private, would it still work if I add the appropriate setter and getter functions?
Upvotes: 0
Views: 57
Reputation: 9678
int main() {
vector<Octagon> octagons;
Octagon o;
o.setCoordinates();
octagons.push_back(o);
//how do I access x from octagons?
// either via an integer index
for(size_t i = 0; n < octagons.size(); ++i)
{
for(size_t j = 0; j < octagons[i].coordinates.size(); ++j)
{
std::cout << octagons[i].coordinates[j].x << '\n';
}
}
// or a range based for loop
for(auto& octagon : octagons)
{
for(auto& coord : octagon.coordinates)
{
std::cout << coord.x << '\n';
}
}
return 0;
}
Generally speaking though, you usually want to hide direct access to internal data where possible (so that the public interface describes actions). It usually makes the class easier to work with.
This is NOT something I'd recommend, but if you want to manually manage the memory yourself, you can do:
vector<Octagon*> octagons;
Octagon* ptr = new Octagon;
octagons.push_back(ptr);
octagons[0]->Coordinates();
Just make sure to remember to free them again.
for(auto ptr : octagons)
delete ptr;
Imho, you'd be better off with std::vector<Octagon>
though, since the memory would be contiguous, and therefore be somewhat faster to process.
Upvotes: 1