Reputation: 223
I created some objects from the class and set default values to its attributes. Then I changed that same objects attribute values to different values. But that update doesn't work for me in the output.
Container* container = TestValueInventor::getContainer();
container->print();
std::vector<ContainerEntry> cont_entry_vector = container->getContainerEntries();
for (vector<ContainerEntry>::iterator it = cont_entry_vector.begin(); it != cont_entry_vector.end(); it++) {
it->updateAmount(6.0);
}
cout << "After the update...." << endl;
container->print();
int pause;
cin >> pause;
return 0;
Above is the main method code. There through the first print()
it will display the default values. Then after the second print()
it should be printed the updated value. But it's still displaying the default value. I have tried to add the pass by reference concepts. But doesn't work for this.
Container * TestValueInventor::getContainer(){
ContainerEntry row1;
row1.setAmount(10);
ContainerEntry row2;
row2.setAmount(50);
Container* container = new Container();
container->addContainerEntry(row1);
container->addContainerEntry(row2);
return container;
}
Above code is the implementation of getContainer()
static method which is in the main method.
void Container::print(){
for (ContainerEntry &row : containerRecord) {
cout << "value:- " << row.getAmount() << endl;
}
}
Above code is to print the output in the terminal. Inside the main function there are two print functions because first one is to print the default values and second one to print the updated values. There both output is the same which is the issue for the client.
std::vector<ContainerEntry> Container::getContainerEntries()
{
return this->containerRecord;
}
Above is the implementation of getContainerEntries()
method.
void ContainerEntry::updateAmount(double amo)
{
this->amount = amo;
}
Above is to update the default amount to 6.0.
Then at last it will not print not 6.0 but the default values which were assigned previously. So how I can make it correct?
Upvotes: 2
Views: 75
Reputation: 409166
The Container::getContainerEntries
function returns a copy of the vector. It should return a reference instead:
std::vector<ContainerEntry>& Container::getContainerEntries() { ... }
And of course you need to assign it to a reference, otherwise you make a copy again:
std::vector<ContainerEntry>& cont_entry_vector = container->getContainerEntries();
Upvotes: 6