S
subramanian100in
Consider the following program x.cpp:
#include <cstdlib>
#include <iostream>
using namespace std;
class Test
{
public:
explicit Test(int arg = 10);
ostream& writeTo(ostream& os) const;
private:
Test(const Test& rhs);
int val;
};
inline Test::Test(int arg) : val(arg)
{
cout << "Test one-argument-ctor called" << endl;
}
inline ostream& Test::writeTo(ostream& os) const
{
return os << val;
}
inline ostream& operator<<(ostream& os, const Test& obj)
{
return obj.writeTo(os);
}
int main()
{
const Test& ref = Test();
cout << ref << endl;
return EXIT_SUCCESS;
}
When I compile this program as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp
I get the following compilation error:
x.cpp: In function `int main()':
x.cpp:12: error: `Test::Test(const Test&)' is private
x.cpp:33: error: within this context
Though the copy ctor of Test is private, the statement
const Test& ref = Test();
involves only taking a 'const reference' to the temporary Test object
created by Test() on the RHS. Since only a reference is made, why does
this statement require the copy ctor ?
Kindly clarify, if necessary with a program example.
Thanks
V.Subramanian
#include <cstdlib>
#include <iostream>
using namespace std;
class Test
{
public:
explicit Test(int arg = 10);
ostream& writeTo(ostream& os) const;
private:
Test(const Test& rhs);
int val;
};
inline Test::Test(int arg) : val(arg)
{
cout << "Test one-argument-ctor called" << endl;
}
inline ostream& Test::writeTo(ostream& os) const
{
return os << val;
}
inline ostream& operator<<(ostream& os, const Test& obj)
{
return obj.writeTo(os);
}
int main()
{
const Test& ref = Test();
cout << ref << endl;
return EXIT_SUCCESS;
}
When I compile this program as
g++ -std=c++98 -pedantic -Wall -Wextra x.cpp
I get the following compilation error:
x.cpp: In function `int main()':
x.cpp:12: error: `Test::Test(const Test&)' is private
x.cpp:33: error: within this context
Though the copy ctor of Test is private, the statement
const Test& ref = Test();
involves only taking a 'const reference' to the temporary Test object
created by Test() on the RHS. Since only a reference is made, why does
this statement require the copy ctor ?
Kindly clarify, if necessary with a program example.
Thanks
V.Subramanian