Short question

C

Charles Keepax

Just a little quick question what is the effect of putting a const after
a member function definition.

Charles
 
V

Victor Bazarov

Charles Keepax said:
Just a little quick question what is the effect of putting a const after
a member function definition.

It makes the function 'const'. Inside it 'this' designates
a constant object. Functions can be overloaded based on that.
For a non-const object non-const function is preferred, for
a const object only a const function will be called.

struct A {
A() {}
void foo() const;
void foo();
};

int main() {
A a;
a.foo(); // non-const is called
const A ca;
ca.foo(); // const is called
}

Doesn't the book on C++ that you're using for study explain
all that?

Victor
 
J

John Harrison

Charles Keepax said:
Just a little quick question what is the effect of putting a const after
a member function definition.

Charles

Its a guarantee that the member function will not alter the object it is
called on. It means that the member function can be called on a const object
or via a const reference or const pointer.

John
 
J

Josephine Schafer

Charles Keepax said:
Just a little quick question what is the effect of putting a const after
a member function definition.
Little quick answer :)
The function does not modify the state of the object/class..
There are two camps on what that implies -
bitwise constness or abstract state constness.
Bitwise constness implies that no member variable gets modified.
For abstract constness consider a class
class A{
public :
void copy () ; // changes what p points to, not p..hence not const

private:
char *p;
};

Even if there is bitwise constness ( p unchanged) but if the contents of
what p points to get changed then
it is not abstract state constness.
 

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,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top