Reputation: 61
I was supposed to create a base class (P2D) that represents a point in two dimensions and a derivate class (P3D) that represents a point in three dimensions. In the first class I created a method this way:
virtual istream& set(istream&); //sets the values
istream& P2D::set(istream& in){
in >> x >> y;
return in;
}
In the second class, instead:
istream& set(istream&); //sets the values
istream& P3D::set(istream& in){
P2D::set(in);
in >> z;
return in;
}
In the main function i thought about putting all points (regardless of whether they are in two or three dimensions) in a vector, and then about setting all points in a while
cycle somehow using the set
method above.
Here is the piece of code in question:
vector<P2D*> points;
bool ans(true);
P2D* p;
while(ans){
cout << "Insert a point" << endl;
p->set();
points.push_back(p);
cout << "Do you want to insert another point? ";
cin >> ans;
}
I know this is wrong and i know why, but is there a chance to overcome that not using the dinamic memory? Am i forced to let the user choice if he wants to insert a two or a three dimension point?
Upvotes: 1
Views: 63
Reputation: 14591
This seems broken to me, as inheritance implies an 'is a' relation, and 3D point definitely is not a 2D point.
This reflects on your problem, as there is no elegant way to do it as you suggest. IMO, user has to decide whether to enter 2D or 3D point, but still it doesn't make sense to keep it as a collection of 2D points.
It all depends on what you intend to do later with points in the collection. Maybe you should have a Point
type as parent of both 2D and 3D point, but it is hard to tell without bigger context.
Upvotes: 2