Home >Backend Development >C++ >How to Define and Implement Interfaces in C ?
Original Question: How do I define a class representing an interface?
Expanded Answer: An interface in C is indeed an abstract base class. However, there is one exception worth considering.
To ensure proper ownership transfer without revealing the concrete derived class, it's recommended to include a virtual destructor in the interface. This destructor doesn't require implementation, as the interface doesn't have specific members.
Example Code:
class IDemo { public: virtual ~IDemo() {} virtual void OverrideMe() = 0; }; class Parent { public: virtual ~Parent(); }; class Child : public Parent, public IDemo { public: virtual void OverrideMe() override { // Custom implementation } };
In this example, both Parent and Child inherit from IDemo, and Child provides a concrete implementation for the OverrideMe function.
Note that while it may seem unusual to define a virtual function as inline, this practice is generally considered safe and beneficial for optimization.
The above is the detailed content of How to Define and Implement Interfaces in C ?. For more information, please follow other related articles on the PHP Chinese website!