Calling memeber function pointer witha constant object.

P

puzzlecracker

OK, here is an example of what I want to accomplish and HOW:

class MyClass
{
public:
void Dummy() const{}

};
typedef void (MyClass::*MemFunc)();

void (const MyClass * instance)
{
MemFunc func=&MyClass::Dummy;
// (instance->*func)(); //gives an error
(const_cast<MyClass *>instance->*func)(); // works

}

Why do compilers (gcc 3 & 4) insist that instnace should be non-const?
and would that const cause issues?

please explain
 
A

Alf P. Steinbach

* puzzlecracker:
OK, here is an example of what I want to accomplish and HOW:

class MyClass
{
public:
void Dummy() const{}

};
typedef void (MyClass::*MemFunc)();

void (const MyClass * instance)
{
MemFunc func=&MyClass::Dummy;
// (instance->*func)(); //gives an error
(const_cast<MyClass *>instance->*func)(); // works

}

Why do compilers (gcc 3 & 4) insist that instnace should be non-const?
and would that const cause issues?

please explain

You forgot 'const' in your typedef.


Cheers & hth.,

- Alf
 
A

Andrey Tarasevich

puzzlecracker said:
OK, here is an example of what I want to accomplish and HOW:

class MyClass
{
public:
void Dummy() const{}

};
typedef void (MyClass::*MemFunc)();

void (const MyClass * instance)
{
MemFunc func=&MyClass::Dummy;
// (instance->*func)(); //gives an error
(const_cast<MyClass *>instance->*func)(); // works

}

Why do compilers (gcc 3 & 4) insist that instnace should be non-const?

Why they insist on it is quite obvious: your 'MemFunc' type is a pointer
to a non-const member function, so expectedly one'd need a non-const
object to invoke that function on.

The real question is why your compiler accepted this initialization

MemFunc func = &MyClass::Dummy;

The RHS os of type 'void (MyClass::*)() const' and LHS is of type 'void
(MyClass::*)()'. There's no standard conversion that'd convert the
former to the latter, meaning that the code is ill-formed and requires a
diagnostic message.
 

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,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top