1. In global scope, this gives error: redefinition of 'f'
#include <iostream>
using namespace std;
void f(int x) { cout << "f" << endl; }
void f(const int x) { cout << "f (const)" << endl; } // error: redefinition of 'f'
int main() { }
2. Defining two copy constructors (one with const
, the other without) compiles
#include <iostream>
using namespace std;
class Foo {
public:
Foo(const Foo&) { cout << "copy (const)" << endl; }
Foo(Foo&) { cout << "copy" << endl; }
};
int main() { }
Question
- Why is #1 a redefinition error but #2 is not?
- For the second example, is there a use case for defining two copy constructors (one with
const
the other without)?
There is a fundamental difference between the two.
One is an overload between
int
andconst int
. It's a value type. There is no semantic difference for the caller, the effect ofconst
only affects the body of the function.The other is a const vs a mutable reference. It has a difference for the caller.
Since its passed by reference, the constness matter for the caller of the function. A function that tries to mutate a const object by reference must be invalid, and a non const object should be passed to the non const overload by default.
With only values, it don't matter at all. It is a new object. No matter the qualifier, it has no meaning for the caller, and it should therefore not care since it only affect the implementation.
You can even add const in definitions only if you want, since it declares the same function:
Live example
As for your second question, I would say that since the addition of rvalue reference, there is little need for a copy constructor to take by mutable reference.
For example,
std::auto_ptr
used to have a constructor that took a mutable reference to transfer ownership, but it created all sorts of problems. But it has been completely replaced bystd::unique_ptr
, which uses rvalue reference to transfer ownership.Rvalue reference ensure that you don't care for the integrity of the copied-from object, and that it's okay to steal off resources from it.