views:

50

answers:

4

I'm trying to create some kind of callback for a class template. The code is like this:

template <typename t>
class Foo {
    void add(T *t) {
        prinf('do some template stuff');
        on_added(t);
    }
    void on_added(T *t) { }
}

struct aaa {}

class Bar : Foo<aaa> {
    void on_added(aaa *object) {
        printf("on added called on Bar");
    }
}

the on_added function on Bar never gets called. What would be the best way to add a callback that a template subclass could optionally override? Thanks

+2  A: 

Your on_added function in Foo needs to be virtual.

Jesse Collins
A: 

You have to make the function virtual if you want calls in the base class to use the implementation in the derived class:

template <typename t>
class Foo {
    ...
    virtual void on_added(T *t) { }
};

Note that this is not special to templates, but applies to all classes.

sth
+4  A: 

Use 'virtual'...

template <typename t>
class Foo {
    void add(T *t) {
        prinf('do some template stuff');
        on_added(t);
    }
    virtual void on_added(T *t) { }
}

struct aaa {}

class Bar : Foo<aaa> {
    void on_added(aaa *object) {
        printf("on added called on Bar");
    }
}
Will A
A: 

Everyone else has already answered the question. Let me just add that adding virtual functions breaks backward compatibility of the class. So, if this is a class that you control and there are no other dependent classes, then yes you can go ahead and convert the on_added to virtual, if not you need to make sure that the dependent modules are also rebuilt.

Gangadhar