hatinacat2000
hatinacat2000

Reputation: 145

C++ How to make a function return the object that called it?

This feels like it should be obvious but I have looked for a while and must not be asking the question right. I am doing an assignment operator overload for a Vector2D class. The function just converts the calling object's x and y coordinates to the vector passed in the argument:

// Vector2D.h
class Vector2D
{
public:

    float x, y;

    Vector2D();
    Vector2D(float x, float y);
.
.
.
Vector2D& operator=(const Vector2D& vec);
.
.
.
}

and

// Vector2D.cpp
.
.
.
Vector2D & Vector2D::operator=(const Vector2D & vec)
{
    this->x = vec.x;
    this->y = vec.y;
    return ? ? ? ? ;
}
.
.
.

What am I supposed to return to make this work? I naively thought return this; would do it but that is not the proper reference.

Upvotes: 0

Views: 77

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93364

I naively thought return this; would do it but that does not the proper reference.

this is a pointer to the current object. To achieve your desired result, simply dereference it: *this.

Upvotes: 3

Related Questions