Reputation: 669
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();
}
Upvotes: 0
Views: 599
Reputation: 1
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
Upvotes: 0
Reputation: 73503
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.
Upvotes: 5
Reputation: 22342
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).
Upvotes: 1
Reputation: 7600
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.
Upvotes: 2