The code compiles successfully, but the program hangs for about 5seconds and the
ID: 3612639 • Letter: T
Question
The code compiles successfully, but the program hangs for about 5seconds and then quits. It's supposed to print things on thescreen in main, but it's hanging up on something in my classimplementation file. The main program basically creates twoobjects (tcc1 and tcc2 and then passes tcc2 into tcc1 using thetcc1.setValue(tcc2) function. Here's the implementation codefor the class called "testCopyConstructor." Anybody see aproblem in this code that would cause it to hang duringruntime? Thanks.#include<iostream>
#include "testCopyConstructor.h"
using namespace std;
testCopyConstructor::testCopyConstructor() //regularconstructor
{
P = new int[100];
Grade = 0;
NGrades = 100;
for(int i = 0; i < NGrades; i++)
{
P[i] = 0;
}
}
testCopyConstructor::testCopyConstructor(consttestCopyConstructor& other) //copy constructor
{
*this = other; //copies all contents of objectusing overloaded assignment
}
testCopyConstructor::~testCopyConstructor() //destructor
{
if(P != NULL)
delete[] P;
}
const testCopyConstructor& testCopyConstructor::operator=(consttestCopyConstructor &rhs) //overloaded assignment operator
{
if(this != &rhs) //Make sure this object isnot the same as rhs object.
{
//delete the dynamicarray.
if(P != NULL)
{
delete[] P;
P = NULL;
}
//copy the staticvariables.
Grade = rhs.Grade;
//copy dynamic variables(if any)
if(NGrades > 0)
{
P = new int[NGrades];
for(int i = 0; i < NGrades; i++)
P[i] = rhs.P[i];
}
//return this newlyminted object to caller
return *this;
}
}
void testCopyConstructor::setValue(testCopyConstructor tcc)
{
Grade = 100;
cout << "Hi!" << endl <<endl;
}
Here's the header file:
#include<iostream>
using namespace std;
class testCopyConstructor
{
public:
testCopyConstructor(); //regular constructor
testCopyConstructor(consttestCopyConstructor& other); //copy constructor
~testCopyConstructor(); //destructor
const testCopyConstructor& operator=(consttestCopyConstructor &rhs); //overloaded assignment operator
void setValue(testCopyConstructor tcc);
private:
int *P;
int Grade, NGrades;
};
Explanation / Answer
I had main code. Anyway, thanks anyways. I think I'vefigured it out. Basically, the problem was with the pointernot being set to NULL in the copy constructor before the overloadedassignment operator was called.