In classes, my book uses examples like
Things like that.Code:GetAge(int itsage) const {return itsage} /*and*/
SetAge(int age) {itsage = int age}
Why would you do this and not jsut combine the functions?
Printable View
In classes, my book uses examples like
Things like that.Code:GetAge(int itsage) const {return itsage} /*and*/
SetAge(int age) {itsage = int age}
Why would you do this and not jsut combine the functions?
>> GetAge(int itsage) const {return itsage}
That should be:
where it returns the member variable.Code:int GetAge() const {return itsage;}
>> Why would you do this and not jsut combine the functions?
How would you combine the functions? How would you be able to tell the difference between codethat wanted to get the current value and code that wanted to change the current value?
Ah good point I think it was just that the book always used them in a row so that there was really no point in having the two.
as a general design point, don't provide getter and setter function for private variables unless you really need it. As soon as you do that, you're essentially exposing them as part of the interface of the class.
for example, in a game you might have a Player class, with a private int member representing player health. Instead of a SetHealth method, it's better to have Damage/Heal/Kill/whatever methods. That way if you decide that health should be a float (for some reason), you don't break the interface
another common idiom:
Code:struct person
{
int
age(void) const
{
return age_;
}
void
age(int set)
{
age_ = set;
}
protected:
int age_;
};