Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pure virtual function have body [duplicate]

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

What is the use to provide a function body for pure virtual functions, if they are not going to be called at all?

like image 875
Vijay Avatar asked Mar 30 '11 04:03

Vijay


People also ask

Does pure virtual function have body?

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

What is the point of a pure virtual function?

A pure virtual function makes it so the base class can not be instantiated, and the derived classes are forced to define these functions before they can be instantiated. This helps ensure the derived classes do not forget to redefine functions that the base class was expecting them to.

What is difference between virtual function and pure virtual function?

A virtual function is a member function in a base class that can be redefined in a derived class. A pure virtual function is a member function in a base class whose declaration is provided in a base class and implemented in a derived class.

Does a pure virtual function return anything?

No. A function is pure virtual if and only if it is declared with = 0 . Show activity on this post. Pure virtual function is function marked with =0 .


2 Answers

Your assumption that pure virtual function cannot be called is absolutely incorrect. When a function is declared pure virtual, it simply means that this function cannot get called dynamically, through a virtual dispatch mechanism. Yet, this very same function can easily be called statically, non-virtually, directly (without virtual dispatch).

In C++ language a non-virtual call to a virtual function is performed when a qualified name of the function is used in the call, i.e. when the function name specified in the call has the <class name>::<function name> form.

For example

struct S  {   virtual void foo() = 0; };  void S::foo()  {   // body for pure virtual function `S::foo` }  struct D : S  {   void foo()    {     S::foo();            // Non-virtual call to `S::foo` from derived class      this->S::foo();      // Alternative syntax to perform the same non-virtual call      // to `S::foo` from derived class   } };  int main()  {   D d;    d.S::foo();    // Another non-virtual call to `S::foo` } 
like image 168
AnT Avatar answered Sep 28 '22 06:09

AnT


"Effective C++" Meyers mentions a reason for a pure virtual function to have a body: Derived classes that implement this pure virtual function may call this implementation smwhere in their code. If part of the code of two different derived classes is similar then it makes sense to move it up in the hierarchy, even if the function should be pure virtual.

see here.

like image 33
Prince John Wesley Avatar answered Sep 28 '22 07:09

Prince John Wesley