Path: utzoo!attcan!uunet!mcsun!unido!ira.uka.de!fuchs From: fuchs@it.uka.de (Harald Fuchs) Newsgroups: comp.lang.c++ Subject: Re: Invoking Member Functions Via Pointers Message-ID: Date: 9 Nov 90 15:30:06 GMT References: <27515@mimsy.umd.edu> Sender: news@ira.uka.de (USENET News System) Organization: University of Karlsruhe, FRG Lines: 88 wilson@brillig.cs.umd.edu (Anne Wilson) writes: >(I tried to post this yesterday, and it has not yet appeared. My >apologies if this appears twice. -aw) Not here. >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 >Can anyone help with this?? I am running g++ V 1.37.1 on a VAX. >I would be **very** grateful for any suggestions! Use real "pointers to members". If you don't know what that is, get a newer C++ book (they were added to the language after 1985). Then it goes something like that: #include #include class Base_class { public: virtual void dfunc () = 0; }; class Derived_class: public Base_class { int d; public: Derived_class (int x): d (x) {} void dfunc () { cout << "Derived_class\t" << d << "\n"; } }; class Container_class { int num; Base_class** list; public: Container_class (int, ...); void apply (void (Base_class::*) ()); }; Container_class::Container_class (register int x, ...): num (x), list (new Base_class*[num]) { cout << num << " elements:"; va_list ap; va_start (ap, x); register Base_class** p = list; while (x--) { *p++ = va_arg (ap, Derived_class*); cout << " " << p[-1]; } va_end (ap); cout << "\n"; } void Container_class::apply (void (Base_class::*funcp) ()) { register int n = num; register Base_class** p = list; // while (n--) ((*p++)->*funcp) (); // Too complicated for AT&T cfront 2.1 while (n--) ((*p)->*funcp) (), p++; } main () { Derived_class D1 (1), D2 (2); cout << "D1@" << &D1 << ", D2@" << &D2 << "\n"; Container_class c (2, &D1, &D2); c.apply (&Base_class::dfunc); } Note that you can only apply a member function of the base class to a Base_class* object, but it can be a virtual member function. -- Harald Fuchs ... *gulp*