Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use-cases of pure virtual functions with body?

I recently came to know that in C++ pure virtual functions can optionally have a body.

What are the real-world use cases for such functions?

like image 424
missingfaktor Avatar asked Apr 09 '10 16:04

missingfaktor


People also ask

Can pure virtual function have a body?

Pure virtual functions (when we set = 0 ) can also have a function body.

What is the use of pure virtual function?

A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in the declaration. An abstract class is a class in C++ which have at least one pure virtual function.

Where do we use virtual functions give its applications?

A virtual function is a member function in the base class that we expect to redefine in derived classes. Basically, a virtual function is used in the base class in order to ensure that the function is overridden. This especially applies to cases where a pointer of base class points to an object of a derived class.

Can we call pure virtual functions using object?

You may call a virtual function as long as it is not a pure virtual function, and as long as you know that what you are calling is the method from the class itself and not expecting any polymorphism. Calling a pure virtual function from a constructor is undefined behaviour even if it has an implementation.


1 Answers

The classic is a pure virtual destructor:

class abstract {   public:      virtual ~abstract() = 0; };  abstract::~abstract() {} 

You make it pure because there's nothing else to make so, and you want the class to be abstract, but you have to provide an implementation nevertheless, because the derived classes' destructors call yours explicitly. Yeah, I know, a pretty silly textbook example, but as such it's a classic. It must have been in the first edition of The C++ Programming Language.

Anyway, I can't remember ever really needing the ability to implement a pure virtual function. To me it seems the only reason this feature is there is because it would have had to be explicitly disallowed and Stroustrup didn't see a reason for that.

If you ever feel you need this feature, you're probably on the wrong track with your design.

like image 166
sbi Avatar answered Oct 13 '22 08:10

sbi