-2
#include<iostream>
using namespace std;

class Test
{
 /* Class data members */
 public:
   Test(Test &t) { /* Copy data members from t*/}
   Test()        { /* Initialize data members */ }
};

Test fun()
{
  cout << "fun() Called\n";
  Test t;
  return t;
}

int main()
{
   Test t1;
   Test t2 = fun();
   return 0;
}

What is wrong with above C++ code? compiler throws following error.
error: no matching function for call to ‘Test::Test(Test)’

Daniel Daranas
  • 22,454
  • 9
  • 63
  • 116
username_4567
  • 4,737
  • 12
  • 56
  • 92

1 Answers1

9

You declared a copy constructor which requires a non-const lvalue. However, fun() returns a temporary and you can't bind a temporary to a non-const lvalue. You probably want to declare your copy constructor as

Test(Test const& t) { ... }
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380