Home >Backend Development >C++ >How to Define and Implement Interfaces in C ?

How to Define and Implement Interfaces in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-04 06:22:40361browse

How to Define and Implement Interfaces in C  ?

Expanding on Interface Declaration 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn