Re: Why '(&b) -> f() ' is static binding?
zhangyafei_kimi@163.com wrote:
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?
The compiler knows that &b can only point to an object of type base, and
not a derived class. Therefor, the compiler can use static binding.
(&b) -> ~base() ;
new (&b) derive ;
(&b) -> f() ;//why this f() is static bound?
Here you trigger UB, because you have re-used the storage of b, and you
use the lvalue b, without meeting all the requirements that are needed
for such usage.
In particular, the new object you created is not of the same type as the
original object.
As the compiler may assume that a program does not invoke UB, the
compiler will most likely just look at the declaration of b and notice
that it can only refer to an object of type base.
base *p = &b ;
p->f() ;//it is easy to understand this line
system("pause");
return 0 ;
Here you have another problem.
At this point, you invoke UB, because you leave the scope of b, but the
storage of b does not contain an object of type base.
}
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?
Because the compiler (rightfully) determines that &b can only refer to
an object of type base.
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.
Have you checked clause 3.8 of the C++ standard? It describes in detail
how you can manipulate the lifetime of objects and what restrictions
you have to keep.
Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]