I
I
Ilya2018-10-01 21:27:50
C++ / C#
Ilya, 2018-10-01 21:27:50

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);
}

An error occurs:
error: no matching function for call to 'Point::Point()'

As I understand it, the compiler wants to define the center_pt variable using the standard constructor, without arguments, but there is none. This is easily solved by adding another constructor call:
Square::Square(double x, double y, double size):center_pt(x/size, y/size)
{...

But if it’s impossible to calculate the values ​​so easily, if these values ​​are calculated in the constructor or the variables are not set, but are read from the sensor, or some other option, when Squareyou can’t get the parameters for before the constructor is executed Point, what should you do then?
Adding a constructor for Pointwithout 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

1 answer(s)
M
Mercury13, 2018-10-01
@Mr_Epic

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;
  }
};

Option 2. Through the pointer, creation and destruction. For simplicity, I will not do this “by hand”, but will use the unique_ptr sole ownership pointer.
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 question

Ask a Question

731 491 924 answers to any question