constant member functions

S

srinivas reddy

Hi,
Can a constant member function be overloaded with its non-constant
equivalent. I mean can void func() be overloaded with void func()
const. If so what behaviour is guaranteed, how does the compiler
resolve ambiguity?, and how could I call a specific variant?

tia,
Srinivas
 
V

Victor Bazarov

srinivas reddy said:
Can a constant member function be overloaded with its non-constant
equivalent.

If that's a question (somehow I got used to seeing '?' at
the ends of questions), then the aswer is 'yes'.
I mean can void func() be overloaded with void func()
const.
Yes.

If so what behaviour is guaranteed, how does the compiler
resolve ambiguity?

There is no ambiguity. Non-const function is preferred when
called for a non-const object. For a const object non-const
function cannot be called.
, and how could I call a specific variant?

By using a cons_cast if the const-ness of the function is
not to your satisfaction. However, casting away const and
then calling a non-const function for a const object will
result in undefined behaviour.

Victor
 
A

Andrey Tarasevich

srinivas said:
...
Can a constant member function be overloaded with its non-constant
equivalent. I mean can void func() be overloaded with void func()
const.
Yes.

If so what behaviour is guaranteed, how does the compiler
resolve ambiguity?, and how could I call a specific variant?
...

For overloading purposes, you can think of member functions as if they
are ordinary functions with an additional implicit 'this' parameter.
When declared as a member of class 'A', method 'void func()' is
equivalent to standalone function 'void func(A* this)' and method 'void
func() const' is equivalent to standalone function 'void func(const A*
this)'. The overloading will work the same way it works for standalone
functions. For non-constant object the first version is called, for
constant objects the second version is called.
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top