On Aug 3, 6:00 am, cxf <cxf....@gmail.comwrote:
class A{
public:
A()
{
func(0);
};
virtual void func(int data)
{
printf("A1 :%d\n",data);
}
virtual void func(int data) const
{
printf("A2 :%d\n",data);
}
};
A().func(1) invoke which function?
The non-const one.
,why?
Because it can. Literally: if all other things are equal, and
two functions differ only by their const-ness, the compiler will
prefer the non-const version whenever it can be called.
I think it is " void func(int data) const", because A() return
a temporary object, which should be const.
Why? You asked the compiler to construct an A, not an A const.
There is no way to request an A const directly, but you can
return one:
extern A f() ;
extern A const g() ;
f().func() ; // invokes non-const function
g().func() ; // invokes const function.
But when it is executed with vc 6.0, it invokes "void func(int
data)"!
As required.
The issues are not trivial, and largely historically
conditionned. But basically, a temporary is something called an
rvalue: if it has non-class type, it has no cv-qualifiers in its
type (but what you can do with it is restricted by the
constraints concerning lvalue and rvalue of the different
operators). If the rvalue has class type, however, things
become more complicated, because const-ness (and volatile-ness)
affect what you can do with it. Since "int f()" returns an int
(and not an int const), "A f()" returns an "A", and not an "A
const". However, while changing the declaration to "int const
f()" does nothing but create confusion in the minds of the
reader (because the return value is an rvalue of non-class type,
and isn't cv-qualified), changing it to "A const f()" does have
an effect (because despite being an rvalue, the temporary must
still be a real object, with address, etc., and there are ways
of getting that address).
Finally, of course, the situation is additionally complicated
because of the rule that you cannot use an rvalue (even if it
has class type) to initialize a non-const reference, but you can
use one (even if it doesn't have class type, and isn't an
"object") to initialize a const reference (which means that,
indirectly, you can get the address of the temporary).
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34