Page 1 of 1

Just another const WTF in I-17.2

Posted: December 18th, 2017, 2:13 pm
by MCanterel
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?

Re: Just another const WTF in I-17.2

Posted: December 18th, 2017, 2:39 pm
by colencon
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;
}
}

Re: Just another const WTF in I-17.2

Posted: December 18th, 2017, 10:47 pm
by albinopapa
//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.

Re: Just another const WTF in I-17.2

Posted: December 19th, 2017, 2:39 am
by MCanterel
Makes sense. TY guys.