Reputation: 12652
Silly question: what is the best way to pass this by value?
Background: Let's use cars and car options. I used to have constructors such as Ford(FordOptions), Honda(HondaOptions). All cars derive from Car, all options from CarOptions. I used to have a car factory that gets passed a pointer to a CarOption, checks the type, produces the appropriate car, and returns a pointer to a generic Car.
I have now changed this so that CarOption has a virtual ProduceCar returning a Car, and every individual car option implements its particular production. So when I get a generic pointer to a car option, I just call CarOptions.ProduceCar and get a generic pointer to a car.
This is all fine, except in the implementation for say FordOption.ProduceCar I need to pass the FordOption instance to the Ford constructor. I can do this by passing "this" and changing the constructur for Ford to accept a pointer to FordOptions instead of FordOptions. However, I'd like it to take FordOptions by value, or at least by reference, but struggle to do so.
Long question for a simple answer I bet. Thanks.
Upvotes: 2
Views: 176
Reputation: 1851
I believe you want to dereference the 'this' pointer. To do so, send *this to your contsructor.
Upvotes: 1
Reputation: 67147
If all you want to do is to path this
by value or reference, just use *this
:
return new Ford(*this);
Upvotes: 1
Reputation: 10969
this
is a regular old pointer. So *this
produces a reference to the object this
points to, which can then be passed however you like.
Upvotes: 1
Reputation: 11989
So you have a CarOption& which you believe is in fact a FordOption& ? Sounds like a job for the dynamic_cast
operator.
Upvotes: 0
Reputation: 11513
You just have to dereference the this
pointer... And depending on the called method, you pass a reference (as in the example), or by value
Ford::Ford(const FordOption &o) {}
Ford FordOption::produceCar() {
return Ford(*this); // <-- Dereference this
}
Upvotes: 4