How is this behavior explained in c++ OOP? [closed]

I have written a Point class and I use this class make a triangle class. The class Point has two attributes the x-coordinate and the y-coordinate. The triangle class has three attributes, the corner points.

Point class:

Point() 
    {
        x = 0;
        y = 0;
    }

    //constructor 2
    Point(double i, double j)
    { 
        x = i; 
        y = j;
    }

Triangle class:

 Triangle()
    {
        a = Point();
        b = Point();
        c = Point();
    }


Triangle(Point i, Point j, Point k) : a(i), b(j), c(k)
    {}

I have written function translate.

Triangle& translate(const Point t)
    {
        this->a + t;
        this->b + t;
        this->c + t;

        return *this;
    }

In my main block I test these functions.

 Triangle t = {{0, 0}, {4, 0}, {0, 4}};
    std::cout << t.b.x << std::endl;
    std::cout << t.b.y << std::endl;

    t.translate(Point{10,10});

    std::cout << t.b.x << std::endl;
    std::cout << t.b.y << std::endl;

output:

4
0
4
0

I expected the values 14 and 10 after the function was called. Because the pointer was modified I thought that the same instance would give the right output after calling the function. This is not the case. Why is this? What do I need to do in order to get 14 and 10 as output while returning *this?

Question: I thought that my function modifies the instance, but it doesn't. How is this behaviour explained.

Question: How do I need to change my function in order to get the right output?



Read more here: https://stackoverflow.com/questions/64958219/how-is-this-behavior-explained-in-c-oop

Content Attribution

This content was originally published by Tim at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: