Hi Jack,
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
Could anyone explain with examples how to use (like the above code
fragment)
the & operator and const inside the prototype? (I know & is return by
value
and const is making the function immutable?)
I'm not entirely sure I understand what you mean, but here are some
examples of how to use references and const in methods.
class Person
{
private:
int m_age;
public:
Person(int age) : m_age(age)
{
}
void setAge(int age)
{
m_age = age;
}
int getAge() const
{
return m_age;
}
};
void GrowOlder(Person& person)
{
person.setAge(person.getAge() + 1);
}
int main()
{
Person p1(10);
GrowOlder(p1);
// p1.m_age is now 11
const Person p2(100);
p2.getAge(); // OK, because getAge is const
p2.setAge(99); // Error, because setAge is non-const and p2 is const
}
So, marking a method as const makes it possible for clients to call it on
const instances of the class. The compiler also checks that a const method
does not modify the state of the object, so you can't write to m_age from
getAge() in the example above.
References are used to let a function modify one of its arguments. By
making the person argument a reference in GrowOlder above, we can modify
the actual person passed in at the call site.
Hope that helps.
--
Best Regards,
Kim Gr?sman