Pointer to Member Function of derived class

V

Vulcan

<code>
class Base {
};

class Class1 : public Base{
public:
void Function1();
}


void Tracker(Base b, void (Base::*callback)());

int main(){
Class1 o1;
Tracker(&o1, &Class1::Function1);
}
</code>

The above code doesn't work because Function1 is only declared in the
derived class. Is there a way around this? I want to be able to have a
member function of a derived class as callback.
 
V

Vulcan

<code>
class Base {

};

class Class1 : public Base{
public:
void Function1();

}

void Tracker(Base b, void (Base::*callback)());

int main(){
Class1 o1;
Tracker(&o1, &Class1::Function1);}

</code>

The above code doesn't work because Function1 is only declared in the
derived class. Is there a way around this? I want to be able to have a
member function of a derived class as callback.

I am looking for a way to provide a function Function1 with an object
Object1 and a member function of that object as a callback.

The full story:
I have several classes representing graphical objects like rectangle,
line, circle all derived from a common base say BObject. I need to be
able to modify any selected shape on the screen by dragging with the
mouse. I want to create one function called Tracker which will handle
mouse move events and update the shape on the screen by calling a
function on the object being modified.

Writing mouse tracking code per shape will take up too much repetitive
code. I felt it would be better for the tracker to have a callback
which it can call every time the mouse moves and then call ReDraw().
 
D

Daniel Pitts

Vulcan said:
<code>
class Base {
};

class Class1 : public Base{
public:
void Function1();
}


void Tracker(Base b, void (Base::*callback)());

int main(){
Class1 o1;
Tracker(&o1, &Class1::Function1);
}
</code>

The above code doesn't work because Function1 is only declared in the
derived class. Is there a way around this? I want to be able to have a
member function of a derived class as callback.
You might have to go the route of using a template for Tracker.
template<typename T>
void Tracker(T &base, void (T::*callback)());

Alternatively, you might want to have callback be a functor, and omit b
altogether:

template<typename callback>
void Tracker(callback &c) { c(); }

struct Class1Function1Callback {
Class1 &o;
Class1Function1Callback(Class1 &o) : o(o) {}
void operator() { o.Function1(); }

}
int main() {
Class1 o1;
Tracker(Class1Fucntion1Callback(o1));
}
 

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,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top