Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!uunet!nih-csl!lhc!mimsy!brillig.cs.umd.edu!wilson From: wilson@brillig.cs.umd.edu (Anne Wilson) Newsgroups: comp.lang.c++ Subject: Invoking Member Functions Via Pointers Message-ID: <27515@mimsy.umd.edu> Date: 7 Nov 90 17:13:48 GMT Sender: news@mimsy.umd.edu Reply-To: wilson@brillig.cs.umd.edu (Anne Wilson) Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 71 (I tried to post this yesterday, and it has not yet appeared. My apologies if this appears twice. -aw) AUGHH! I am having a devil of a time trying to invoke a pointer to member function through an object which is a base class object for the derived class to which the member function belongs. The whole thing is so compliciated, I have tried to "paraphrase" an example: class Base_class { } class Derived_class : public class { void new_function; } typedef void (*v_fn_ptr) (void *); class Container_class { Base_class* *list; // array of pointers to Base_class elements Container_class (int obj_count, ... ); void apply (v_fn_ptr); // apply function to each element in list } Derived_class D1, D2; Container_class c (2, &D1, &D2); // create c // Idea is to apply new_function to both D1 and D2 c.apply (&Derived_class::new_function); // compiles, but crashes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I have running code which does something very similar and works correctly, the only difference being that the apply function is called on Base_class objects rather than Derived_class objects. So I suspect the binding between the Derived_class member function and a list item, which is also of type Derived_class, is not happening properly. I have been trying the trick of letting the function appear like any old function and passing it the address of the Derived_class object as its first argument, but to no avail. I typed in the following example from Straustrup, and (guess what ...) it ran fine. #include class cl { public: char* val; void print (int x) { cout << val << " " << x << nl;}; cl (char *v) {val = v;} }; typedef void (*PROC) (void*, int); main () { cl z1 ("z1"); cl z2 ("z2"); PROC pf1 = PROC (&z1.print); PROC pf2 = PROC (&z2.print); z1.print(1); (*pf1) (&z1,2); z2.print(3); (*pf2) (&z2,4); } Can anyone help with this?? I am running g++ V 1.37.1 on a VAX. I would be **very** grateful for any suggestions! Anne Wilson