I am learning C++, and doing a little game i had to pass a object as a parameter by reference, and first i did something like:
void function(OBJECT* obj) {
std::cout << obj->x;
}
then:
OBJECT obj(2);
function(&obj); //2
The parameter is a pointer and i call the function with the parameter by reference. That i thought. But in the internet y have seen calling the function with no reference, and in the def:
function(OBJECT &obj) {
std::cout << obj.x;
}
So, whats the difference between this:
class Road {
public:
int limit_r, limit_l;
Road(int _limit_r, int _limit_l) : limit_r(_limit_r), limit_l(_limit_l) {}
};
class Car {
int x;
public:
Car(int _x) : x(_x) { };
void move(Road &r);
};
void Car::move(Road &r) {
while (this->x >= r.limit_r) {
this->x++;
}
}
int main() {
Road road(0, 20);
Car car(road.limit_r);
car.move(road);
return 0;
}
And this:
...
class Car {
...
public:
...
void move(Road* r); //Changed
};
void Car::move(Road* r) { //Changed
while (this->x >= r->limit_r) { //Changed
this->x++;
}
}
int main() {
Road road(0, 20);
Car car(road.limit_r);
car.move(&road); //Changed
return 0;
}
Is there any difference? Which is better or more correct?
why the way to call a property or method changes? (road->limit_r and road.limit_r)
Thank you.