Connecting Tech Pros Worldwide Help | Site Map

constant member functions

srinivas reddy
Guest
 
Posts: n/a
#1: Jul 19 '05
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
Victor Bazarov
Guest
 
Posts: n/a
#2: Jul 19 '05

re: constant member functions


"srinivas reddy" <srinivasreddy_m@yahoo.com> wrote...[color=blue]
> Can a constant member function be overloaded with its non-constant
> equivalent.[/color]

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

Yes.
[color=blue]
> If so what behaviour is guaranteed, how does the compiler
> resolve ambiguity?[/color]

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.
[color=blue]
>, and how could I call a specific variant?[/color]

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


Andrey Tarasevich
Guest
 
Posts: n/a
#3: Jul 19 '05

re: constant member functions


srinivas reddy wrote:[color=blue]
> ...
> Can a constant member function be overloaded with its non-constant
> equivalent. I mean can void func() be overloaded with void func()
> const.[/color]

Yes.
[color=blue]
> If so what behaviour is guaranteed, how does the compiler
> resolve ambiguity?, and how could I call a specific variant?
> ...[/color]

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.

--
Best regards,
Andrey Tarasevich
Brainbench C and C++ Programming MVP

Closed Thread