Re: Why need copy constructor to be public here?
sy8111.public@gmail.com wrote:
In following code:
#include <iostream>
using namespace std;
class Test
{
public:
Test(int n) {cout << "ctor" << endl;}
Test& operator=(const Test& aList) {cout << "assign" << endl; return
*this;}
operator int() {cout << "operator int"<< endl; return 5;}
Test(const Test&) {cout << "copy ctor" << endl;}
};
int main()
{
Test b(3);
Test a = (int)b;
return 0;
}
output is:
ctor
operator int
ctor
I can see that copy constructor is not called. Now I change copy
constructor to be private, and recompile g++ gives following errors:
c.cpp: In function `int main()':
c.cpp:12: error: `Test::Test(const Test&)' is private
c.cpp:20: error: within this context
c.cpp:12: error: `Test::Test(const Test&)' is private
c.cpp:20: error: within this context
c.cpp:20: error: initializing temporary from result of
`Test::Test(int)'
So why can't I put copy constructor as private here even it is not used?
The simple answer is because the standard says so. In fact, the
formal semantics of copy initialization (i.e. a declaration
where the initializer is preceded by an equals sign) is to
convert the value to the correct type (here, use the conversion
constructor int->Text), and then copy construct the variable
with the results of the conversion. The compiler is explicitly
allowed to elide the copy, as an optimization, but even if it
does, the copy constructor must be accessible.
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]