views:

288

answers:

2

Here's the deal. I have a big class hierarchy and I have this one method that is extended all the way through. The method always has to look at one or two more variable at each new level and these variable depend on the actual class in the hierarchy. What I want to do is check those two extra variables then call the superclass's version of that same function. I want to be able to define this function as all it's immediate children will use it, but I want to force any children of that class to have to redefine that method (because they will have to look at their new data members)

So how would I write this? I usually use =0; in the .h file, but I assume I can't use that and define it...

+8  A: 

Actually you can declare a function as purely virtual and still define an implementation for it in the base class.

class Abstract {
public:
   virtual void pure_virtual(int x) = 0;
};

void Abstract::pure_virtual(int x) {
   // do something
}


class Child : public Abstract {
    virtual void pure_virtual(int x);
};

void Child::pure_virtual(int x) {
    // do something with x
    Abstract::pure_virtual();
}
Bill the Lizard
Maybe my brain is too small, but changing the signature of pure_virtual in the derived class has confused me. What does it illustrate?
Steve Jessop
onebyone good catch oO i didn't spot it. i suspect it's a typo?
Johannes Schaub - litb
The original question had extra data being passed to the function defined in the child classes. Now that you mention it, I think it should be in the base class too.
Bill the Lizard
+8  A: 

You can provide a definition for a pure virtual function. Check GotW #31 for more information.

Firas Assaad
+1 for that link - very interesting.
Mark Ransom