Register    Login    Forum    Search    FAQ

Board index » Everything




Post new topic Reply to topic  [ 4 posts ] 
Author Message
 Post Posted: December 18th, 2017, 2:13 pm 
 

Joined: December 8th, 2017, 8:48 pm
Posts: 10
In Intermediate 17.2, I was playing around with the ApplyDamageTo() function to try to understand the const modifier.
Code:
   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?


Top 
 Profile  
Reply with quote  
 Post Posted: December 18th, 2017, 2:39 pm 
 

Joined: February 13th, 2014, 2:24 pm
Posts: 32
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;
}
}


Top 
 Profile  
Reply with quote  
 Post Posted: December 18th, 2017, 10:47 pm 
 

Joined: February 28th, 2013, 3:23 am
Posts: 2970
Location: Oklahoma, United States
Quote:
//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


Top 
 Profile  
Reply with quote  
 Post Posted: December 19th, 2017, 2:39 am 
 

Joined: December 8th, 2017, 8:48 pm
Posts: 10
Makes sense. TY guys.


Top 
 Profile  
Reply with quote  
Display posts from previous:  Sort by  
 
Post new topic Reply to topic  [ 4 posts ] 

Board index » Everything


 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for: