Sasha
Sasha

Reputation:

How do I call a member function pointer using a pointer to a constant object?

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 instance should be non-const? Would that const_cast cause issues?

FYI: instance` is not necessarily const, I just don't want a callee to mess with it.

What is happening here?

Upvotes: 3

Views: 198

Answers (2)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507005

The error is in the line before. Change the typedef to

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

To make it a pointer to a const member function type.

The difference might be more clear when considering this code and how it works:

typedef void FunctionType() const;
typedef FunctionType MyClass::*MemFunc;

A member-function pointer in particular is actually just a special case of a member-pointer in general. For a const member function, the function type of the member function is different than for a non-const member function. That is why the types have to match.

Upvotes: 7

James Curran
James Curran

Reputation: 103515

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

Here you are defining a pointer to a function which might modify its object.

MemFunc func=&MyClass::Dummy;

Here you are assigning a function which won't change it's object to such a pointer. This is legal, since not changing is a subset of might change.

(instance->*func)();

Here you are trying to call a function which might change its object, using an object which cannot be changed.

You will need to change the definition of MemFunc

Upvotes: 0

Related Questions