In C++ is it possible to have a defined purely virtual function?
Asked Answered
R

2

6

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...

Renault answered 7/12, 2008 at 23:32 Comment(0)
F
9

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();
}
Foreign answered 7/12, 2008 at 23:52 Comment(3)
Maybe my brain is too small, but changing the signature of pure_virtual in the derived class has confused me. What does it illustrate?Panter
onebyone good catch oO i didn't spot it. i suspect it's a typo?Much
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.Foreign
J
9

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

Jessejessee answered 7/12, 2008 at 23:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.