c++ - Private members of objects in an array not-modifiable -


i know there's lot of literature on this, still can't figure out. let me start general description of problem, , i'll post mcve.

description: have array of objects - can values of private members, not set them. think it's how i'm writing setter methods, i'm not sure how modify make right.

main.cpp

store walmart; vip vip;  //  set vip points 100 vip.setpoints(100); walmart.setvip(vip, 0); cout << "points (before): " << walmart.getvip(0).getpoints() << endl;  //  set vip points 200 walmart.getvip(0).setpoints(200); cout << "points (after): " << walmart.getvip(0).getpoints() << endl; 

console output

points (before): 100 points (after): 100  // <-- hoping 200! 

store.cpp

void store::setvip(vip vip, int index) {     this->vip[index] = vip; } vip store::getvip(int index) {     return this->vip[index]; } 

vip.cpp

void vip::setpoints(double points) {     this->points = points; } double vip::getpoints() {     return this->points; } 

after googling problem, i'm convinced problem how return vip object in store.cpp file getvip(int index) getter method - haven't yet succeeded in returning modifiable reference.

look @ signature of 'getvip' method:

vip store::getvip(int index) { ... } ^^^  

you returning 'vip' object value, means returning copy of object. calling method on copy result in modification of copy, not of actual object in array. want instead (as have mentioned) return reference object, so:

vip& store::getvip(int index) { return vip[index]; }    ^     "reference vip object" 

this way, able modify object within array. if don't want modify object, still viable return reference, prevent unnecessary copies, in case return const reference:

const vip& store::getvip(int index) const { return vip[index]; } ^^^^^    ^  "constant reference vip object" 

note in 3 cases, body of method exact same thing, return type of method defines whether copy created or not.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -