quick question about C++ function

P

Pingke

bool foo (T const & x,T const & y) const{
...
}

the third const means what?

thanks in advance!
 
F

Frederick Gotham

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 */
}
 
F

Frank Puck

Pingke said:
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
 
P

Pingke

Frederick said:
Pingke posted:



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 */
}

thank you very much, very clear
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,477
Members
44,898
Latest member
BlairH7607

Latest Threads

Top