tags:

views:

62

answers:

1

I have a C++ class which is meant to be inherited. All its children will inherit a method:

class Record {
public:
    RETTYPE* all();
};

class Child : public Record {
    int age;
    char *name;
};

int main() {
    Child boo;
    Child boos* = boo->all(); // Pointer to array of Children
    return 0;
};

How can I make a method return (a pointer to) itself? I can't just say Record all(); as Child is not Record. The method will never be called on Record. Always on some class inherited from Record.

Can anyone help me? Thanks.

+2  A: 

Here's one way

class Record {

};

template<class T>
class RecordOf : public Record {
public:
    T* all();
};

class Child : public RecordOf<Child> {
    int age;
    char *name;
};

Each subclass now has an all method that returns the exact type. You can put methods that are virtual and have the same signature in subclasses in Record and ones that depend on exact type in RecordOf.

It's called the Curiously Recurring Template pattern

http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

Lou Franco