Page 1 of 1

Quick question

Posted: Thu Apr 26, 2007 3:02 am
by LwSiX
Hi there,

i was going over some code examples of a characterclass and saw this

Code: Select all

class CharacterClass
{
public:
    boolean isMagicUser() const;
};
what exactly is that and shouldnt it be...

Code: Select all

class CharacterClass
{
public:
	bool isMagicUser() { return m_bMagicUser; }
private:
    bool m_bMagicUser;
};
or is that something completely different?

Thanks.

Posted: Thu Apr 26, 2007 8:49 am
by Perceval
The keyword const is used to make sure that this function won't modify any variables of its class. It's just an additionnal protection.
I guess this code was somewhere in a header file :

Code: Select all

class CharacterClass
{
public:
    boolean isMagicUser() const;
}; 
This is just a protype. This function is probably declared in another file, like this (don't forget the const keyword here) :

Code: Select all

class CharacterClass
{
public:
   bool isMagicUser() const { return m_bMagicUser; }
private:
    bool m_bMagicUser;
}; 

Posted: Sun Apr 29, 2007 9:06 am
by LwSiX
This may be a ridiculous question, and you can laugh at me if you want, but how in the world would a function that only returns a variable be used to accidentally set or modify a variable?

Posted: Sun Apr 29, 2007 10:17 am
by Perceval
This is definitly not a ridiculous question. To be more precise, when a member function is declared as const, it means that :
- it can't modify data of the class
- it can't call member functions that are not const, because these functions could be able to modify the object data.
- and what i've forgotten (but it's really important), is that a non-const member function can't be called with a const argument, because a non-const member function could try to modify some members of the object.

Now, in your case, it's clear that the isMagicUser() function won't change any member, but you will understand that this keyword can be apply to more complicated functions. (sorry, i don't have any example in mind :cry: )