-6

I came across this question in debug practice test. Please help me understand the output.

foo(a) produces: "Copying" and "foo called" where as bar(a) produces: "bar called". Can anyone explain the working of these two calls?

#include <stdio.h>
#include <stdlib.h>

class A
{
public:
    A() : val_(0) {}
    ~A () {}
    A(const A& c)
    {
        if(&c != this)
        {
            printf("Copying \n");
            this->val_ = c.val_;
        }
    }
    void SetVal(int v) {this->val_ = v;}
    int GetVal() {return (this->val_);}

private:
    int val_;
};

static void foo(A a)
{
    printf("foo called \n");
    a.SetVal(18);
}
static void bar(A& a)
{
    printf("bar called \n");
    a.SetVal(22);
}

int main(int, char**)
{
    A a;
    a.SetVal(99);    
    foo(a);    
    bar(a);
    return 0;
}
Bo Persson
  • 90,663
  • 31
  • 146
  • 203
Flying Dutchmann
  • 85
  • 1
  • 2
  • 3

2 Answers2

0

The signature void foo(A a) passes A by value, thus it will make a copy of the input parameter and then use that in the function.

void bar(A& a) passes a reference to the input parameter, thus the argument that you call the function with will be used in the function.

Edit: For a more complete explanation this link might help: http://courses.washington.edu/css342/zander/css332/passby.html

CJCombrink
  • 3,738
  • 1
  • 22
  • 38
0
void foo(A a) uses "pass by value". Which invokes copy constructor. Hence printing: "Copying" and then "foo called"

void bar(A& a)uses "pass by reference". Which does not invoke copy constructor. Hence printing only: "bar called"

See the difference

Community
  • 1
  • 1
NightFurry
  • 358
  • 1
  • 17