Instrument the student_info class to count how objects are created, copied, assi
ID: 3691037 • Letter: I
Question
Instrument the student_info class to count how objects are created, copied, assigned, and destroied.
To do this add static variables to the Student_info class. (e.g. static int myVar = 0;) These variables are shared among all the objects created. You will need to create constructors, a copy constructor, an assignment operator, and a destructor that all increment the static variables.
Use this instrumented class to execute the student record programs from Section 6.2. Important note: You will find all of the source code from the text to be used as the basis for this project at: https://github.com/bitsai/book-exercises/tree/master/Accelerated%20C%2B%2B/chapter06
You will, of course, need to make changes to suit your system and to instrument the code.
Test data can be found at: https://github.com/bitsai/book-exercises/tree/master/Accelerated%20C%2B%2B/data
At the end of the program print out the static variable values. Since they are public you can get at them using the class name (e.g Student_info::myVar).
Explanation / Answer
Well, I see that Student_info is a struct here. Lets add a static variable to it. The headerfile will look as following when we add constructor, copy constructor,
assignment operator and destructors.
struct Student_info {
std::string name;
double midterm, final;
std::vector<double> homework;
static int myVar; //declaration is done here
//Constructors
Student_info();
Student_info(std::string sname, double m, double f, std::vector<double> hw);
//Copy Constructor
Student_info(const Student_info &obj);
//Assignment Operator
Student_info& Student_info::operator=( const Student_info& other);
//Destructor
~Student_info();
}
};
Now, all the implementation will go into the source file i.e. cc file. We initialize our static variable here as well as implement all the functions.
int Student_info::myVar = 0; //static variable initialization
//constructors
Student_info::Student_info() : name(""), midterm(0.0), final(0.0)
{ myVar++; }
Student_info::Student_info(std::string sname, double m, double f, std::vector<double> hw): name(sname), midterm(m), final(f), homework(hw)
{ myVar++; }
//Copy Constructor
Student_info::Student_info(const Student_info &obj)
{
name = obj.name;
midterm = obj.midterm;
final = obj.final;
homework = obj.homework;
myVar++;
}
//Assignment operator
Student_info::Student_info& Student_info::operator=( const Student_info& other ) {
name = other.name;
midterm = other.midterm;
final = other.final;
homework = other.homework;
myVar++;
return *this;
}
//Destructor
Student_info::~Student_info() {
myVar++;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.