L
LRS Kumar
Stoustrup, in The C++ Programming Language, has the following example
in 11.7:
string g (string arg) // string passed by value using copy
constructor
{
return arg; //string returned (using copy constructor)
}
int main()
{
string s = "Newton"; //string initialized (using copy constructor)
s = g(s);
}
The first two comments are clear. I was wondering why the third
comment says that the initialization uses the copy constructor.
If that was the case, wouldn't the following code also have been
initialized using the copy constructor?
#include <iostream>
class X {
int i;
public:
X() { i=0; std::cout << "defcon\n";}
X(int n) {i=n; std::cout << "intcon\n";}
X(const X& x) {i = x.i; std::cout << "copycon\n";}
};
int main()
{
X x = 2;
}
Instead, the output is: intcon
LRSK
in 11.7:
string g (string arg) // string passed by value using copy
constructor
{
return arg; //string returned (using copy constructor)
}
int main()
{
string s = "Newton"; //string initialized (using copy constructor)
s = g(s);
}
The first two comments are clear. I was wondering why the third
comment says that the initialization uses the copy constructor.
If that was the case, wouldn't the following code also have been
initialized using the copy constructor?
#include <iostream>
class X {
int i;
public:
X() { i=0; std::cout << "defcon\n";}
X(int n) {i=n; std::cout << "intcon\n";}
X(const X& x) {i = x.i; std::cout << "copycon\n";}
};
int main()
{
X x = 2;
}
Instead, the output is: intcon
LRSK