Topic: Question about the validity of forming and using member pointers


Author: kristov@arcor.de (Christoph Schulz)
Date: Tue, 14 Feb 2006 19:04:12 GMT
Raw View
Hello!

In a comp.lang.c++.moderated thread the following code was deemed illegal=
:

 #include <iostream>
 using namespace std;

 class Base
 {
 protected :
  virtual void f () {cout << "Base" << endl;}
 };
 struct Derived2 : Base
 {
 protected :
  virtual void f () {cout << "D2" << endl;}
 };
 struct Derived : Base
 {
  void call_f (Base *base)
 /*** (1) ***/ {(base->* (&Derived::f)) ();}
 };
 int main ()
 {
  Derived d;
  Derived2 d2;
  d.call_f (&d2);
 }

The line (1) was said to engender undefined behavior:

Greg Herlihy wrote:
> This code is legal only in the sense that it will compile. The behavior
> of its execution however is undefined. It is undefined because the
> Derived::call_f() routine applies a member pointer of class Derived to
> an object whose dynamic class (Derived2 in this case) contains no
> members of class Derived.
>=20
> =A75.5/4 covers this situation:
>=20
> "If the dynamic type of the object does not contain the member to which
> the pointer refers, the behavior is undefined."

I'm not sure whether this is true. As I argued, the expression
"&Derived::f" is a member pointer to Base::f because the class Derived
does not directly contain a member named "f" (and the rules of =A75.3.1/2
apply). And the dynamic type of the object "base" is Derived2, which
obviously contains Base::f. So I think that the snippet above is legal.
Can anyone clarify this issue?

By the way, the root of the discussion was the question not whether the
program above is legal but whether it should be disallowed, as it could
be seen that the protection of Base::f is undermined. I proposed to
think about a change (and its consequences, naturally) in =A75.3.1/2 to
make &Derived::f be of type void(Derived::*)() even if Derived only
inherits the member "f". (As johnchx2 pointed out, there is already a DR
on this (#203).)

Regards,
  Christoph

---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html                       ]