The Partridge Family were neither partridges nor a family. Discuss.
-
MCanterel
- Posts: 10
- Joined: December 8th, 2017, 8:48 pm
Post
by MCanterel » December 18th, 2017, 2:13 pm
In Intermediate 17.2, I was playing around with the ApplyDamageTo() function to try to understand the const modifier.
Code: Select all
void ApplyDamageTo(MemeFighter& target, int damage) const
{
std::cout << target.name << " takes " << damage << " damage." << std::endl;
// hp += damage; //can't do this because function is const
target.hp -= damage; //...BUT then why can target.hp be changed?
//Is the const modifier ONLY for this-> object?
if (!target.IsAlive())
{
std::cout << target.name << "Is dead, and starting to stink!" << std::endl;
}
}
So why am I able to modify target.name in this function? Does const only apply to the member data of this-> instance?
-
colencon
- Posts: 35
- Joined: February 13th, 2014, 2:24 pm
Post
by colencon » December 18th, 2017, 2:39 pm
that const at last mean you can't modify any thing in object who call ApplyDamageTo(). In that funtion you must do dame to target not yourself, target must have a funtion CalculateDame() not const
void CaculateDame(int dame)
{
hp -= dame;
}
void ApplyDamageTo(MemeFighter& target, int damage) const
{
std::cout << target.name << " takes " << damage << " damage." << std::endl;
target.CaculateDame(damage);
if (!target.IsAlive())
{
std::cout << target.name << "Is dead, and starting to stink!" << std::endl;
}
}
-
albinopapa
- Posts: 4373
- Joined: February 28th, 2013, 3:23 am
- Location: Oklahoma, United States
Post
by albinopapa » December 18th, 2017, 10:47 pm
//Is the const modifier ONLY for this-> object?
Yes, const at the end of a member function signature means, 'this' is const and therefore can't change anything that 'this' refers to:
this->hp += damage // error function is const
Target is declared MemeFighter& target, here target is not const so it can be modified.
If it had been declared const MemFighter& target, you would not have been allowed to modify anything in target either.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com
-
MCanterel
- Posts: 10
- Joined: December 8th, 2017, 8:48 pm
Post
by MCanterel » December 19th, 2017, 2:39 am
Makes sense. TY guys.