Non-static member functions have an extra parameter called the
implicit object parameter. The implicit object parameter is always a reference to the class the function is a member of.
This means there is a close correspondence between member and non-member functions. It's easiest to show by example:
| Non-static member function signature | Corresponding non-member function signature |
| void f() | void f(A& this_) |
| void f() const | void f(A const& this_) |
| void g() & | void g(A& this_) |
| void g() && | void g(A&& this_) |
| void g() const& | void g(A const& this_) |
| void g() const&& | void g(A const&& this_) |
| void g() const volatile& | void g(A const volatile& this_) |
| ... | ... | |
Within a member function, keyword
this is equivalent to
&this_ in the corresponding non-member.
It follows the normal initialization rules |
Nearly, the exception is that line 5 compiles below, despite that line 6 is an error:
1 2 3 4 5 6 7
|
struct A { void f() {}; };
void f(A& this_) {};
int main()
{
A{}.f(); // okay
f(A{}); // error: cannot bind non-const lvalue reference of type A& to rvalue of type A
}
|
The exception probably exists to allow line 5 to compile. Notice that the signatures of
A::f and
::f correspond in the table above.
1. What is meant by "we can't bind this to a const object"?
2. What is meant by "we can't call an ordinary member function on a const object"? |
It means that given this declaration:
const struct A { void f() {} } a;
The statement
a.f();
Doesn't compile because it tries to pass an object with type
const A to a function like
void f(A& this_). This would throw away
const.
Here's another example of the same:
1 2 3 4 5 6
|
void f(int& x) { x = 1; }
int main()
{
const int x = 2;
f(x); // error
}
|