In C++ is it possible to have a defined purely virtual function?
-
20-08-2019 - |
Question
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...
Solution
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();
}
OTHER TIPS
You can provide a definition for a pure virtual function. Check GotW #31 for more information.