pointer to member function and pointer to constant member function

B

Bob Hairgrove

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;
}
 
F

Fraser Ross

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

Fraser.
 
B

Bob Hairgrove

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.
 
F

Fraser Ross

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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top