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...
A pure virtual function is a function that must be overridden in a derived class and need not be defined. A virtual function is declared to be “pure” using the curious =0 syntax. For example: class Base {
A pure virtual function is a member function of base class whose only declaration is provided in base class and should be defined in derived class otherwise derived class also becomes abstract. Classes having virtual functions are not abstract. Base class containing pure virtual function becomes abstract.
A pure virtual function is declared by assigning 0 in declaration.
C has no native syntax for virtual methods. However, you can still implement virtual methods by mimicking the way C++ implements virtual methods. C++ stores an additional pointer to the function definition in each class for each virtual method.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With