I have a class called Rectangle which holds two pointers to objects of the class Point2D.
class Rectangle: public GeoObjekt
{
private:
Point2D* lu;
Point2D* ro;
public:
Rectangle(Point2D lu, Point2D ro);
}
Rectangle::Rectangle(Point2D lu, Point2D ro) {
this->lu = &lu;
this->ro = &ro;
}
To create an object of this class, I call the following line:
Rectangle rectangle(Point2D(0, 0), Point2D(2, 1));
The constructor is working fine, but when I try to access Point2D* lu; or Point2D* ro;, I get an access violation exception:
Exception thrown at 0xFEDC8589 in Rectangle.exe: 0xC00005: Access violation while executing at position 0xFEDC8589.
I checked it with the debugger and the values inside Point2D* lu; or Point2D* ro; are completely different from the values they initially had. They change after leaving the constructor.
Can someone tell me what I am doing wrong?
Note: The line Rectangle rectangle(Point2D(0, 0), Point2D(2, 1)); should remain as it is.
Point2Dinstead.operator newexcept in placement new expressions and always prefer smart pointers and containers such asstd::vectorandstd::arrayto raw pointers and C arrays. Do this constantly and you will notice your programs will basically never crash, unless you do something really bad. Nowadays in C++17 and C++20 I mostly use pointers as a replacement forstd::optional<T&>(which is not legal).