1

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.

Emile
  • 51
  • 3
  • When you pass a pointer, it can be `nullptr`. This is not the case for a reference; and it's the case in most situations. – Ripi2 Dec 30 '21 at 20:08
  • `function(class OBJECT &obj) {`: Please do _not_ use the `class` specifier when you want to refer to a type. Only use `class` in the definition or forward-declaration of the class (or in template parameters). It has potential additional effects that may mask mistakes. Instead just ``function(OBJECT &obj) {`` – user17732522 Dec 30 '21 at 20:08
  • `class OBJECT` can be shortened to `OBJECT` here and in most scenarios, except for declaring the class itself. – HolyBlackCat Dec 30 '21 at 20:09

0 Answers0