While pure virtual functions are generally understood to lack implementations, certain scenarios allow for their definition within the base class.
In the code snippet you provided:
class A { public: virtual void f() = 0; }; void A::f() { cout << "Test" << endl; }
The function A::f() is declared as pure virtual with an implementation. This is permissible by the C language, although it raises questions about its purpose.
Pure virtual functions with implementations serve a specific purpose. By providing a default implementation in the base class, derived classes can:
Here's an example:
class B : public A { virtual void f() { A::f(); // Calls the base class implementation } };
The use of pure virtual functions with implementations is uncommon but can be beneficial in scenarios where:
While providing implementations for pure virtual functions in the base class is permitted by the C language, it is not a common practice. Understanding the purpose and implications of this technique allows you to utilize it when appropriate.
The above is the detailed content of When and Why Would You Implement a Pure Virtual Function in C ?. For more information, please follow other related articles on the PHP Chinese website!