pointer to member function and pointer to constant member function

Discussion in 'C++' started by Fraser Ross, Aug 14, 2004.

  1. Fraser Ross

    Fraser Ross Guest

    Are these pointers the same?

    Fraser.
    Fraser Ross, Aug 14, 2004
    #1
    1. Advertising

  2. On Sat, 14 Aug 2004 12:16:12 +0100, "Fraser Ross"
    <fraserATmembers.v21.co.unitedkingdom> wrote:

    >Are these pointers the same?


    No. Try this:

    #include <iostream>
    #include <ostream>

    using namespace std;

    class A
    {
    public:
    void func() { cout << "Non-const func()." << endl; }
    void func() const { cout << "Const func()." << endl; }
    };

    typedef void (A::* pf)();
    typedef void (A::* cpf)() const;

    int main()
    {
    A a;
    const A b;
    pf fp = &A::func;
    cpf cfp = &A::func;

    (a.*fp)(); // OK, outputs "Non-const func()."
    (a.*cfp)(); // OK, outputs "Const func()."
    // (b.*fp)(); // this line won't compile:
    // "Cannot convert 'const A *' to 'A *'"
    (b.*cfp)();
    return 0;
    }


    --
    Bob Hairgrove
    Bob Hairgrove, Aug 14, 2004
    #2
    1. Advertising

  3. Fraser Ross

    Fraser Ross Guest

    My compiler is working correctly with constness. const is usually on the
    left of * so the syntax differs from the usual pointer syntax.

    Fraser.
    Fraser Ross, Aug 14, 2004
    #3
  4. On Sat, 14 Aug 2004 14:08:31 +0100, "Fraser Ross"
    <fraserATmembers.v21.co.unitedkingdom> wrote:

    >const is usually on the
    >left of * so the syntax differs from the usual pointer syntax.


    What do you mean by that? Consider the following:

    (1) const char * pcc;
    (2) char * const cpc;
    (3) const char * const cpcc;

    Another equivalent (and possibly better, less ambiguous) way of
    writing (1) and (3) would be:

    char const * pcc;
    char const * const cpcc;

    Otherwise, they all mean something very different.

    --
    Bob Hairgrove
    Bob Hairgrove, Aug 14, 2004
    #4
  5. Fraser Ross

    Fraser Ross Guest

    Constant pointer to constant member function:
    void (A::* const cpf)() const;

    Constant pointer to non-constant member function:
    void (A::* const cpf)();

    In the first example the const is not on the left of *.

    Fraser.
    Fraser Ross, Aug 14, 2004
    #5
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    4
    Views:
    332
    Keith Thompson
    Dec 14, 2006
  2. Stephen Howe
    Replies:
    2
    Views:
    278
    Stephen Howe
    Nov 6, 2012
  3. somenath
    Replies:
    10
    Views:
    259
    James Kanze
    Jul 2, 2013
  4. somenath
    Replies:
    2
    Views:
    145
    somenath
    Aug 29, 2013
  5. G G
    Replies:
    3
    Views:
    78
    Ben Bacarisse
    Apr 20, 2014
Loading...

Share This Page