Search code examples
c++ooppointerspass-by-referencepass-by-value

Swap value of two attributes of two objects


I'm learning C++ (coming from Python) and I'm trying to understand how objects interact with each other. I wanted to create a class 'Point', that has two attributes (x and y coordinate) and give it a method that can swap the coordinates of two points (see my code below). With the given code the coordinates of the point p1 are changed to those of p2, but the coordinates of p2 remain unchanged. Can anyone help me and explain how I can achieve this?

Thanks in advance!

#include<iostream>
using namespace std;

//Class definition.
class Point {
public:
    double x,y; 

    void set_coordinates(double x, double y){
    this -> x = x; 
    this -> y = y;
    }

    void swap_coordinates(Point point){
        double temp_x, temp_y;

        temp_x = this -> x;
        temp_y = this -> y;

        this -> x = point.x;
        this -> y = point.y;

        point.x = temp_x;
        point.y = temp_y;
    }
};

//main function.

int main(){

Point p1,p2;

p1.set_coordinates(1,2);
p2.set_coordinates(3,4);

cout << "Before swapping the coordinates of point 1 are (" << p1.x << ","<< p1.y<<")\n";
cout << "and the coordinates of point 2 are ("<< p2.x << ","<< p2.y << ").\n";

p1.swap_coordinates(p2);

cout << "After swapping the coordinates of point 1 are (" << p1.x << ","<< p1.y<<")\n";
cout << "and the coordinates of point 2 are ("<< p2.x << ","<< p2.y << ").\n";

return 0;
}

Solution

  • The parameter point of swap_coordinates is declared as pass-by-value, it's just a copy of the argument and any modification on it has nothing to do with the original argument.

    Change it to pass-by-reference.

    void swap_coordinates(Point& point) {
    //                         ^
        ...
    }