0

Except for the fact that it can be called from the derived class overridden method, the pure virtual function doesnot seem to be able to be called anywhere! What then, is the use of its body? Eg.

class base
{
    public:
    virtual void fun()=0
    {
        cout<<"I have been called from derived class"<<endl;
    }
};
class derived:public base
{
    public:
    void fun()
    {
        cout<<"I am the derived class"<<endl;
        base::fun();

    }
};
void main()
{
    derived d;
    d.fun();
}
Ashwyn
  • 659
  • 1
  • 6
  • 18

4 Answers4

5

It is used in the exact way you mentioned in the question, that there is some common logic that can be reused by the derived classes but at the same time you want to force the derived classes to provide the implementation for the non-common part.

Naveen
  • 74,600
  • 47
  • 176
  • 233
2

It forces derived classes to implement it, while still providing derived implementations with a common behaviour that you don't want invoked from anywhere else than derived classes.

anthonyvd
  • 7,329
  • 4
  • 30
  • 51
1

Pure virtual methods are meant to act as completely abstract methods akin to other languages, such as Java and C#. A C++ class filled with only pure virtual methods is representative of an interface from other languages.

Giving them a body is an abuse of that ideal, and it defeats the purpose. If the base class wants to provide functionality to only its children, then it should do so through a protected, non-pure virtual method (can still be virtual if it makes sense).

pickypg
  • 22,034
  • 5
  • 72
  • 84
0

This question is propably a duplicate of C++ pure virtual function have body I've seen this primarily used with pure virtual destructors (which need an implementation). Another good answer that explains cases beyond the pure virtual destructor use can be found here: (Im)pure Virtual Functions

Community
  • 1
  • 1
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190