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;
}