Quick question

If you are a new Irrlicht Engine user, and have a newbie-question, this is the forum for you. You may also post general programming questions here.
Post Reply
LwSiX
Posts: 22
Joined: Wed Jan 17, 2007 2:24 pm

Quick question

Post 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.
Perceval
Posts: 158
Joined: Tue May 30, 2006 2:42 pm

Post 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;
}; 
LwSiX
Posts: 22
Joined: Wed Jan 17, 2007 2:24 pm

Post 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?
Perceval
Posts: 158
Joined: Tue May 30, 2006 2:42 pm

Post 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: )
Post Reply