-2

Why constructor of class A isn't called when object of this class is passed as an argument to function taking the argument by value?

class A
{
public:
    A()
    {
        cout << "A\n";
    }
};

void f_n(A val)
{

}

int main()
{
    A a;
    f_n(a);
    return 0;
}
There is nothing we can do
  • 23,727
  • 30
  • 106
  • 194

1 Answers1

0

This is because copy constructor is used in this context. To check it add explicit implementation:

A(A const&)
{
    std::cout << "A const&\n";
}  

You have not defined one but compiler synthesizes copy constructor for you. But there are cases when it is not generated.

marcinj
  • 48,511
  • 9
  • 79
  • 100