I am currently working in C++ and I face this challenge. Here is a code of my class in the header file:
class PID
{
private:
int PID;
int total;
public:
PID(); // Constructor
int returnPID(); // Returns PID.
};
Here is the code declaration in cpp file:
PID::PID()
{
PID=INT_MAX;
total=0;
}
int PID::returnPID()
{
return PID;
}
And here is the declaration and the initialization in main of a table contaning pointers to objects of the class PID:
PID* table[1000000];
for (int i=0; i<1000000; i++)
{
table[i]=new PID;
}
So I suppose this uses the constructor I have created above to set the PID to MAX_INT. When I try to access the content of table[i].PID using returnPID within the initialization for everything works great, something like this:
for (int i=0; i<1000000; i++)
{
table[i]=new PID;
int display=table[i]->returnPID();
cout<<display<<endl;
}
The problem occurs when I am trying to access table[i] contents outside and after the initialization for. My main crashes and it returns a number (-1073741571) as an error. It seems like not even one command from the main is executed. Here is a sample of the code that seems to reproduce the problem:
for (int i=0; i<1000000; i++)
{
table[i]=new PID;
}
for (int i=0; i<1000000; i++)
{
int display=table[i]->returnPID();
cout<<display<<endl;
}
I have been working on this for more than two hours without coming to any solution and it just doesn't seem logical. Anyone have any explanation for this?
EDIT: Any table with less than 1.000.000 spots will work correctly. Maybe it has something to do with this although I still don't see the connection.
error: field ‘int PID::PID’ with same name as class...avoid it....privatevariable....and that by the way was my gcc compiler...I was trying to see whats wrong with your code....