Answer the question
In order to leave comments, you need to log in
How to set a class property to be an instance of another class if its values are not known during initialization?
There is a class like this primitive classes:
// Point.h
class Point
{
public:
Point(double x, double y);
double x_coord;
double y_coord;
};
// Square.h
class Square
{
public:
Point center_pt;
Square(double x, double y, double size);
};
// Square.cpp
Square::Square(double x, double y, double size)
{
center_pt = *new Point(x-size/2, y-size/2);
}
error: no matching function for call to 'Point::Point()'
Square::Square(double x, double y, double size):center_pt(x/size, y/size)
{...
Square
you can’t get the parameters for before the constructor is executed Point
, what should you do then? Point
without parameters is not suitable, since in a real task this is an external library and it is not allowed to change it.
Answer the question
In order to leave comments, you need to log in
center_pt = *new Point(x/size, y/size);
Memory leak. No one in "si with crosses" will clean up all these new for you.
That's right:
(Well, of course, I don't understand what these x/size and y/size mean, but the joke is on him.)
Approximately this is how objects are reassigned if they still have the = operation. I.e…
class Geolocator {
public:
Point coords;
bool isReliable;
Geolocator() : coords(0,0), isReliable(false) {}
void getFromSensor() {
coords = Point(100, 100);
isReliable = true;
}
};
class Geolocator {
public:
std::unique_ptr<Point> coords;
void getFromSensor() {
Point pt(100, 100);
if (coords) {
*coords = pt;
} else {
coords.reset(new Point(pt));
}
// а если и операции = у Point нет, то можно
// coords.reset(new Point(100, 100));
}
void declareUnreliable() {
coords.reset();
}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question