In: Computer Science
Use the following class for the following problem. The only purpose of the class is to display a message both when the constructor is invoked and when the destructor is executed.
class Trace
{
public:
Trace(string n);
~Trace();
private:
string name;
};
Trace::Trace(string n) : name(n)
{
cout << "Entering " << name << "\n";
}
Trace::~Trace()
{
cout << "Exiting " << name << "\n";
}
Requirement:
Extend the class Trace with a copy constructor and an assignment operator, printing a short message in each. Use this class to demonstrate
a. the difference between initializationTrace t("abc");
Trace u = t;
and assignment.
Trace t("abc");
Trace u("xyz");
u = t;
b. the fact that all constructed objects are automatically destroyed.
c. the fact that the copy constructor is invoked if an object is passed by value to a function.
d. the fact that the copy constructor is not invoked when a parameter is passed by reference.
e. the fact that the copy constructor is used to copy a return value to the caller.
Programming language: C++
Requirement: please tightly follow up the rules by covering points from a-e.
Answer:
Source Code:
#include <iostream>
using namespace std;
class Trace
{
private: char *name;
public:
Trace(char *n);
~Trace();
Trace(const Trace &t);
void operator =(const Trace &t);
};
Trace:: Trace(char *n) // Parametrized constructor
{
name = n;
cout<<endl<<"Parametrized Constructor
Executed."<<endl;
cout<<"Name:"<<name;
}
Trace:: ~Trace() // Destructor
{
cout<<endl<<"Destructor
Executed"<<endl<<"Exsiting:"<<name;
}
Trace :: Trace(const Trace &t) // Definition of Copy
constructor
{
cout<<endl<<"Copy Constructor
Executed"<<endl<<"Copy the value of one object to
another."<<endl;
name = t.name;
}
void Trace :: operator = (const Trace &t) // Overload
assignment operator
{
cout<<endl<<"Operator Overloading Done"<<"Using
of = operator to copy two objects"<<endl;
name = t.name;
cout<<"Name of First Object:"<<name;
cout<<endl;
cout<<"Name of Second
Object:"<<t.name<<endl;
}
int main()
{
Trace t1("Ram"); // Calls Parametrized Constructor
Trace t2("Sham"); // Calls Parametrized Constructor
Trace t3(t2) ; // Calls the copy Constructor Value is pass by
referce only because c++ allow to pass only referece in copy
constructor
t1 = t2; // Calls the Overloading Function
return 0;
}
OUTPUT:
Dear Student If you get any type of error or have any problem with source code when executing then explain in comment section. We will be there to solve your problems.
Thumbs Up if you are satisfy with answer.
Thankyou