Re: Why '(&b) -> f() ' is static binding?
zhangyafei_kimi@163.com schrieb:
{ Double-spacing corrected. -mod }
I am puzzled by a face test, which source code is like below:
#include <iostream>
using namespace std ;
class base
{
public:
virtual void f() { cout << "base::f()" << endl ; }
};
class derive : public base
{
public:
void f() { cout << "derive::f()" << endl ; }
};
int main()
{
base b ;
(&b) -> f() ;//why this f() is static bound?
Who says it is? The compiler can prove that this calls base::f because b
is of type base, so there is no need for a virtual dispatch. I might
also do a virtual dispatch, the result would be the same.
(&b) -> ~base() ;
new (&b) derive ;
This is pretty problematic. You're creating an object of type "derived"
in a memory region that is possibly not large enough to hold it.
Basically, you are cheating the compiler.
(&b) -> f() ;//why this f() is static bound?
See above. b is still an object of type base, just that you have cheated
and forced the compiler to place an object of type "derived" in its
memory. However, how is it supposed to know?
base *p = &b ;
p->f() ;//it is easy to understand this line
system("pause");
return 0 ;
}
The result of this short program is so peculiar and like this:
base::f()
base::f()
derive::f()
In my opinion, the result of expression '(&b)' is a 'base*' type, so
it will cause a polymorphic behavior. But why '(&b) -> f();' is static
bound?
After referring some authoritative documents, I still can not find the
reason. So I am doubting that the standards did not clearly state this
situation. I am eager to know the reason and the fact.
Probably because there is no need to. You're triggering UB.
So long,
Thomas
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]