In: Computer Science
White the class Trace with a copy constructor and an assignment operator, printing a short message in each. Use this class to demonstrate
the difference between initialization
Trace t("abc");
Trace u = t;
and assignment.
Trace t("abc");
Trace u("xyz");
u = t;
the fact that all constructed objects are automatically destroyed.
the fact that the copy constructor is invoked if an object is passed by value to a
function.
the fact that the copy constructor is not invoked when a parameter is passed
by reference.
the fact that the copy constructor is used to copy a return value to the caller.
Programming language: C++
Requirement: please cover points 1-5.
#include<iostream>
using namespace std;
class Trace{
string x;
public:
string getx()
{
return x;
}
void setx(string x)
{
this->x =
x;
}
Trace()
{
x = "";
}
Trace(string x)
{
this->x =
x;
}
Trace(Trace const &T)
{
cout<<"Copy Constructor invoked\n";
this->x =
T.x;
}
Trace operator=(Trace const
&T)
{
cout<<"Assignment operator invoked\n";
this->x =
T.x;
}
~Trace()
{
}
};
int main()
{
Trace t("abc");
Trace u = t;
Trace v;
v = t;
}
//output