Passing objects to methods

Discussion in 'Programmer's Corner' started by asilvester635, Apr 16, 2017.

  1. asilvester635

    Thread Starter Member

    Jan 26, 2017
    67
    2
    Can anyone check my logic here. I just want to know whether I'm understanding the logic behind this code.

    When you pass your Car object to a method declared like this:
    void cost(Car f) const throw();
    The method cannot modify the Car object because the method is marked by const. Also a copy of the object is passed to the parameter of the cost function.

    When you pass your Car object to a method declared like this:
    void cost(const Car& f) const throw();
    The method cannot modify the Car object because the method is marked by const. This time, a copy is not passed to the parameter of the cost function. Instead, the actual Car object is passed to the parameter list and is marked by const, which means that the cost function cannot modify this Car reference object.
     
  2. MrSoftware

    Active Member

    Oct 29, 2013
    656
    182
    I'm not clear on your const throw() syntax, I've not used that before and my c++ compiler doesn't like it.

    BUT that said; assuming this is c++, in the first example you're passing a copy of object "f". You can do whatever you want to it inside your method, but you will only modify the local copy. So the caller will not see the changes in its copy of "f".

    In the second example you're passing a reference to "f", a pointer to the memory that "f" occupies. But you've declared that you're referencing a const object, so the compiler won't let you change "f" inside of cost() because you told the compiler that it was a reference to a constant (read-only) object.
     
Loading...