@helios
1. Regarding the copy constructor signature:
I'm not sure what to say here:
A (const A&)
is NOT the canonical signature for the copy constructor, at least that's what the course I'm reading says. By the way, I'm talking about the C++ institute.
Here's what they say:
"The copying constructor is a specific form of constructor designed to make a more or less literal copy of an object. You can recognize this constructor by its distinguishable header.
Assuming that a class is called A, its copying constructor will be declared as:
A(A &)
This means that the constructor expects one parameter to be a reference to an object whose content is intended to be copied to the newly created object."
Are they maybe wrong here, in the sense that maybe
A ([const] A&)
would be the real canonical copy constructor signature?
I mean, does maybe the true theoretical signature specify a "const", but which is optional?
I found myself some mistakes in their course, I just want the truth.
Here's an example program using this signature (
A(A &)
) for a copy constructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
using namespace std;
class Class {
int data;
public:
Class(int value) {
cout<<"Constructing "<<value<<endl;
data = value;
}
Class(Class &source) {
cout<<"Copying\n";
data = source.data;
}
~Class(void) {
cout<<"Destroying "<<data<<endl;
}
void increment(void) { data++; }
int value(void) { return data; }
};
int main(void) {
Class o1(123);
Class o2 = o1;
Class o3(o2);
o1.increment();
cout << o1.value() << endl;
cout << o2.value() << endl;
cout << o3.value() << endl;
return 0;
}
|
The program works fine and the output I get is this:
1 2 3 4 5 6 7 8 9 10 11 12
|
user:~$ g++ -fno-elide-constructors -o test test.cpp
user:~$ ./test
Constructing 123
Copying
Copying
124
123
123
Destroying 123
Destroying 123
Destroying 124
user:~$
|
2. Regarding the "a" variable:
Yes "a" is an L-VALUE, but any L-VALUE is ALSO an R_VALUE.
That's why I said in both cases a non-const reference is being initialized from an rvalue.
But I see now this lvalue-rvalue issue is not exactly as straight-cut as I thought.
I will have to do a lot more reading... :(