jas305
jas305

Reputation: 99

How to know the value of a reference

I recently started learning C++ and I can't understand the following code (it's a copy constructor, deep copy):

Car::Car(const Car &c){
this->_make = new string(*(c._make));
this->_model = new string(*(c._model));
this->_year = new int(*(c._year));
}

Here, we are passing by reference so why are we adding the "*" here: *(c._make), shouldn't it just be c._make, as passing by reference already gives the value, what does the * do in this case?

Upvotes: 0

Views: 58

Answers (3)

Ric
Ric

Reputation: 151

It's hard to see why a deep copy is necessary for 3 simple variables. Nevertheless if they were defined as pointers in the class then they need to be dereferenced otherwise you would be copying the address of the values instead of the values themselves. The fact that the object is being passed by reference doesn't mean that its member variables are being referenced as well.

Deep copying is useful when the class includes dynamically allocated arrays, or other classes, etc. But for simpler classes with simple variables (no pointers), a shallow copy should be enough.

Upvotes: 1

Remy Lebeau
Remy Lebeau

Reputation: 595762

The * is not being applied to the passed Car object itself, but to its 3 pointer members, _make, _model, and _year. The pointers are being dereferenced when the members are being passed to their respective copy constructors.

Upvotes: 1

Eugene
Eugene

Reputation: 7188

You need * in this->_make = new string(*(c._make)); because make was defined as a pointer:

class Car
{
   string* make;
   //...
};

This design is pointless - it would be better to hold string by value:

class Car
{
   string make;
   //...
};

In which case the code in question would look like:

    Car::Car(const Car &c){
    this->_make = c._make;
//...
}

with no * anywhere.

Upvotes: 1

Related Questions