I am trying to understand why the following code fails to update the recordID in the Record objects. Is it something about the Record pointers returned by the vector class? Can someone explain what is going on? Thanks in advance for any help.
I am using gcc (4.4.1) on Linux.
Cheers
Sanders
The output:
Changing record no from -1 to 9
The new record no is -1
Changing record no from -1 to 9
The new record no is -1
Changing record no from -1 to 9
The new record no is -1
Changing record no from -1 to 9
The new record no is -1
Changing record no from -1 to 9
The new record no is -1
The Code:
#include <vector>
#include <iostream>
using namespace std;
class Record
{
public:
// Constructors
Record() { RecordNo = -1; }
~Record() {}
// Accessors
int getRecordNo() { return RecordNo; }
void setRecordNo(int value) { RecordNo = value; }
private:
int RecordNo;
};
int main(int argc, char *argv[])
{
vector<Record> dataset;
Record *record;
int newRecordNo = 9;
// Create a few records to add to the RecordCol
record = new Record();
dataset.push_back(*record);
record = new Record();
dataset.push_back(*record);
record = new Record();
dataset.push_back(*record);
record = new Record();
dataset.push_back(*record);
record = new Record();
dataset.push_back(*record);
// Iterate thru the records making changes as we go
vector<Record>::iterator pRecord = dataset.begin();
while (pRecord != dataset.end()) {
cout << "Changing record no from " << ((Record)*pRecord).getRecordNo() << " to " << newRecordNo << endl;
((Record)*pRecord).setRecordNo(newRecordNo);
cout << "The new record no is " << ((Record)*pRecord).getRecordNo() << endl;
++pRecord;
}
Cheers and thanks for the reply. I think that my types are okay but it seems that it will always pay to double check. Also thanks for the tip about code blocks.
Castaway,
Thanks. That fixes my problem. I didn't realise that casting created a new temp object but I guess that that makes sense. I thought that I needed the cast but when I took it away it worked. So 'cheers' to you too. Problem solved and more thanks.