Home >Backend Development >C++ >Can Pure Virtual Functions in C Have Implementations, and Why Would You Do That?
Pure Virtual Functions: Implementation and Purpose
In C , pure virtual functions are typically associated with declaring a method's interface without providing its implementation. However, it's possible to have a pure virtual function with an implementation, as illustrated below:
class A { public: virtual void f() = 0; }; void A::f() { cout << "Test" << endl; }
While this code is syntactically valid, its purpose and usage require further explanation.
Purpose of Providing an Implementation for a Pure Virtual Function:
A base class can define an implementation for a pure virtual function, even though derived classes are required to provide their own implementations. The purpose of this implementation can be:
How to Invoke the Base Class Implementation:
Derived classes can invoke the base class implementation of a pure virtual function using a fully-scoped name:
class B : public A { virtual void f() { // class B doesn't have anything special to do for f() // so we'll call A's // note that A's declaration of f() would have to be public // or protected to avoid a compile time problem A::f(); } };
Use Case:
Consider a scenario where there's a reasonable default behavior for a method. However, the class designer desires for this default behavior to be invoked only explicitly. Providing an implementation for a pure virtual function in the base class allows derived classes to access and use this default behavior as needed.
Note:
While it's technically possible to provide an implementation for pure virtual functions, it's an uncommon practice and can lead to confusion. Therefore, it's generally recommended to avoid doing so unless there's a clear and justifiable reason.
The above is the detailed content of Can Pure Virtual Functions in C Have Implementations, and Why Would You Do That?. For more information, please follow other related articles on the PHP Chinese website!