Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 493
Chad Avatar asked Dec 07 '08 23:12

Chad


People also ask

Can we define pure virtual function?

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 {

Can you define a pure virtual function in base class?

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.

How do you create a pure virtual function?

A pure virtual function is declared by assigning 0 in declaration.

Are there virtual functions in C?

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.


1 Answers

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();
}
like image 184
Bill the Lizard Avatar answered Oct 17 '22 00:10

Bill the Lizard