Write 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.
Programing language: C++
Requirement: provide answer to cover 1-5.
Code:
#include<iostream>
#include<string>
using namespace std;
class Trace
{
private:
string str;
public:
Trace(string s) //parameterised constructor to initialize variable
{
str=s;
}
// Copy constructor
Trace(const Trace &p2){ // this will copies value of one class object1 to
str = p2.str; // another class object
}
string getstr(){ //this method is use to print value of class object
return str;
}
};
int main()
{
Trace p1("Hello"); // Parameterised(Normal) constructor is called here
Trace p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors and copied constructor
cout << "For object p1 : " << p1.getstr()<<endl; //this will print value of p1 that is created by calling constructor
//this will print value of p2 that is created by copy constructor
cout << "For object p2 genrated by copy constructor : " << p2.getstr()<<endl;
Trace p3("Hello1");
p1=p3; //assignment of object
cout << "For object p3 : " << p3.getstr()<<endl; //this will print value of p3,created by calling constructor
//this will print value of p3,created by calling constructor after assignment
cout << "For object p1 after assignment of object p3 : " << p1.getstr();
return 0;
}
Output:
Get Answers For Free
Most questions answered within 1 hours.