delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1999/09/01/01:08:38

From: horst DOT kraemer AT snafu DOT de (Horst Kraemer)
Newsgroups: comp.os.msdos.djgpp
Subject: Re: Function pointers in C++
Date: Tue, 31 Aug 1999 16:45:16 GMT
Organization: [Posted via] Interactive Networx
Lines: 112
Message-ID: <37cbe2f3.66942854@news.snafu.de>
References: <37CBBE53 DOT EECABDD5 AT club-internet DOT fr>
NNTP-Posting-Host: n164-189.berlin.snafu.de
X-Newsreader: Forte Free Agent 1.11/32.235
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

On Tue, 31 Aug 1999 13:36:51 +0200, flupke <schawat AT club-internet DOT fr>
wrote:

> I don't know if i'm doing a "c++ misunderstanding" or if it's a djgpp
> problem, but here is my problem anyway.
> When i execute this piece of code:
 
> ***********************
> #include <iostream.h>
> 
> class glou
> {
> public:
>     int c;
> 
>     glou()
>     {
>         c = 0;
>         a = &b;
>     }
> 
>     void (*a)();
> 
>     void b()
>     {
>         c++;
>     }
> };
> 
> int main()
> {
>     glou blou;
> 
>     cout << blou.c << endl;
> 
>     blou.a();
>     cout << blou.c << endl;
> 
>     blou.b();
>     cout << blou.c << endl;
> 
>     return 0;
> }

The correct syntax handling this situation is


#include <iostream.h>

class glou
{
public:
  int c;
  glou()
  {
    c = 0;
    pmf = &glou::b;          // !!!
  }
  void (glou::*pmf)();       // !!!
  void b() { c++; }
};

int main()
{
    glou blou,blou1;

    void (glou::*pmf1)() = &glou::b;

    cout << blou.c << endl;

    (blou.*blou.pmf)();        // calling though blou's pmf
    cout << blou.c << endl;

    blou.b();
    cout << blou.c << endl;

    (blou.*pmf1)();            // calling though local pfm1
    cout << blou.c << endl;

    (blou.*blou1.pmf)();       // calling through blou1's pmf
    cout << blou.c << endl;

    return 0;
}


You absolutely need a pointer of type

  	void (glu::*)()

in order to call a non-static member function of b's type by pointer.

You have to call the function through the pointer using the .*
operator (or the ->* operator if the calling object is addressed
through a glue*)

Note that the .* or ->* operator is _not_ a kind-of . or -> operator,
i.e. it does _not_ select fields of the object. Note that the pointer
may be defined outside of the class (pmf1) or in another object
(blou1.pmf).


.*  and ->* have a lower precedence than the () operator. Therefore
you have to put brackets around the function expression

	(blou.*blou.pfm)()

before applying the function call operator ().

Regards
Horst

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019