I am learning about classes in C . I came across the following statement from the standard:
During overload resolution, non-static cv-qualified member function of class X is treated as a function that takes an implicit parameter of type lvalue reference to cv-qualified X if it has no ref-qualifiers or if it has the lvalue ref-qualifier. Otherwise (if it has rvalue ref-qualifier), it is treated as a function taking an implicit parameter of type rvalue reference to cv-qualified X.
The above statement seems to imply that for a const
qualified non-static member function of a class X
will have an implicit parameter of type const X&
.
But then i also came across:
The type of
this
in a member function of classX
isX*
(pointer to X). If the member function is cv-qualified, the type of this iscv X*
(pointer to identically cv-qualified X). Since constructors and destructors cannot be cv-qualified, the type of this in them is alwaysX*
, even when constructing or destroying a const object.
So according to the above second quote the implicit this parameter for a const qualified non-static member function of class X
has type const X*
.
My question is that why is there such a difference. I mean during overload resolution for a const qualfied nonstatic member function, why is the implicit parameter considered as a const X&
and not simply a const X*
which seems to be the actual type of this
.
CodePudding user response:
The implicit object parameter is not the same as this
. this
is a pointer referring to the object on which the member function was called while the implicit object parameter is the imagined first parameter of the member function, which is passed the object expression in the member function call (whats left of .
in the member access expression) and so should be a reference parameter.
It wouldn't make sense to use a pointer for the implicit object parameter. It would make it impossible to overload the function on value category of the object expression. If a member function is &&
-qualified, the implicit object parameter is a rvalue reference, so that if the object expression is a rvalue overload resolution correctly overload with a &
-qualified member function.
So the implicit object parameter is const T&
in your example, but this
has type const T*
. There is no contradiction.