In C++ the default behaviour of a method is passing parameters by value. e.g.
void DriveWith(Car myCar)
myCar is a copy of what's passed in. Now think about why did the writers make myCar a copy instead of the actual thing that's passed in? It's good software engineering practise at work. Loose coupling. Simply put just imagine you're a parent with a tenacious 18 year old. He takes your sports car for a spin and runs into an accident. Now because the car that he drove, is your actual car, it's been damaged. Taking this to a different level altogether if the car that he drove is a copy of your sports car, and he damages it somehow, well since it's only a copy, your car is never damaged!
If that only applies in the real world.
Of course you can also pass in myCar by reference, which means you pass in the actual car.
This would look like
void DriveWith(Car& myCar)
Why would you do this in C++? Well it's quicker to pass in the actual thing for one. You don't have to make a copy. And this makes perfect sense, using the above example, it would be extremely time consuming to make an exact copy of your car and then passing it to your 18 year old to drive. Even if it's not car, say watch, shoes, whatever, it would be time consuming to make an exact copy of the same thing instead of passing the actual thing, right?
Now let's say you want your 18 year old to do some shopping, you want them to use the car, but not damage the car, so you give them a copy of the car. To put groceries in, you give them a bag, but you don't give them a copy of the bag, you give them the actual bag, so that they can put stuff in it and it won't disappear. We don't care about the car, if they damage it, it doesn't affect the original car, but we want the groceries, so we pass the actual thing in.
void GoShoppingWith(Car myCar, Bag& shoppingBag);
Now you can get your 18 year old to drive the car without worries, and the only thing you have to worry is them buying the right items to put into the shoppingBag. :)
It's just a pity you can't do that in the real world, well, you can, but it would be very time consuming to create copies of things. Just like in the programming world!
No comments:
Post a Comment