By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,797 Members | 1,848 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,797 IT Pros & Developers. It's quick & easy.

quick question about C++ function

P: n/a
bool foo (T const & x,T const & y) const{
...
}

the third const means what?

thanks in advance!

Jun 26 '06 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Pingke posted:
bool foo (T const & x,T const & y) const{
...
}

the third const means what?

thanks in advance!

This is a member function, and it belongs within a class.

By placing "const" after a member function's name, you indicate that the
function can be invoked on a const object of the class. By default, no
member function can be invoked on a const object of a class, so you have
to explicitly enable this functionality by writing "const" after the
function signature.

class ArbitraryClass {
public:

void ConstFunc() const {}

void NonConstFunc() {}

};
int main()
{
ArbitraryClass obj1;

obj1.ConstFunc(); /* No problem */
obj1.NonConstFunc(); /* No problem */
ArbitraryClass const obj2;

obj2.ConstFunc(); /* No problem */
obj2.NonConstFunc(); /* COMPILE ERROR */
}

--

Frederick Gotham
Jun 26 '06 #2

P: n/a

"Pingke" <xl*****@gmail.com> wrote in message
news:11*********************@y41g2000cwy.googlegro ups.com...
bool foo (T const & x,T const & y) const{
...
}

the third const means what?

thanks in advance!

the method does not/cannot change the object this method is being applied to


Jun 26 '06 #3

P: n/a

Frederick Gotham wrote:
Pingke posted:
bool foo (T const & x,T const & y) const{
...
}

the third const means what?

thanks in advance!

This is a member function, and it belongs within a class.

By placing "const" after a member function's name, you indicate that the
function can be invoked on a const object of the class. By default, no
member function can be invoked on a const object of a class, so you have
to explicitly enable this functionality by writing "const" after the
function signature.

class ArbitraryClass {
public:

void ConstFunc() const {}

void NonConstFunc() {}

};
int main()
{
ArbitraryClass obj1;

obj1.ConstFunc(); /* No problem */
obj1.NonConstFunc(); /* No problem */
ArbitraryClass const obj2;

obj2.ConstFunc(); /* No problem */
obj2.NonConstFunc(); /* COMPILE ERROR */
}

--

Frederick Gotham


thank you very much, very clear

Jun 26 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.