1

I'm running this program on DEV C++ and it's showing error of const.. But In Visual Studio its working fine. Now is const important for copy constructor?

#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;
}
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
Asif Mushtaq
  • 3,658
  • 4
  • 44
  • 80
  • This is unrelated to copy constructors. – juanchopanza May 12 '15 at 05:54
  • @juanchopanza it is, second line in `main()` uses copy-initialization and fails to compile. – vsoftco May 12 '15 at 05:57
  • @vsoftco Yes, but the problem has nothing to do with copy constructors. I could provide an example where the same error occurs in a matrix inversion. – juanchopanza May 12 '15 at 05:58
  • Some (especially older) compilers don't enforce the restriction against binding non-`const` references (such as your copy-constructor argument) to temporaries (such as the `Test` returned by `fun()`'s). No big deal, just fix the code so the copy-constructor accepts by `const` reference. VC++ goes out of its way to avoid breaking old code, unless you provide particular command-line options per the answer to the duplicate. – Tony Delroy May 12 '15 at 06:03
  • @juanchopanza At first I thought OP is also asking if it's legal to have a copy constructor that takes its param. by non-const reference. – vsoftco May 12 '15 at 06:07
  • @AsifMushtaq this code compiles since now you are using a lvalue (non-temporary) as the right hand side of the copy constructor in the line `Point p2 = p1;`. Try `Point p2 = Point(0,0);` and it won't compile anymore. But please don't change the code as it makes all answers and comments look completely unrelated to the original question. – vsoftco May 12 '15 at 06:09

1 Answers1

4

The copy constructor is traditionally declared as

Foo(const Foo&);

since it is assumed that a copy doesn't change the object on its right hand side (at least a good copier shouldn't change it, right?)

In standard C++, you cannot bind a temporary to a non-const reference. Visual Studio uses a non-standard extension, and that's why your code compiles, but you should not rely on non-standard extensions.

It is not absolutely necessary to have your copy constructor taking the rhs by const reference, it is also OK to take it by reference. But in that case, you won't be able to perform copy initialization from a rvalue (a temporary basically).

vsoftco
  • 55,410
  • 12
  • 139
  • 252