Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you declare an interface in C++?

How do I setup a class that represents an interface? Is this just an abstract base class?

like image 760
Aaron Fischer Avatar asked Nov 25 '08 16:11

Aaron Fischer


People also ask

How do you declare an interface?

To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and are public and all fields are public, static, and final by default.

What is an interface and how is it declared?

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.

What can we declare in interface?

The Interface Declaration Two elements are required in an interface declaration — the interface keyword and the name of the interface. The public access specifier indicates that the interface can be used by any class in any package.


2 Answers

To expand on the answer by bradtgmurray, you may want to make one exception to the pure virtual method list of your interface by adding a virtual destructor. This allows you to pass pointer ownership to another party without exposing the concrete derived class. The destructor doesn't have to do anything, because the interface doesn't have any concrete members. It might seem contradictory to define a function as both virtual and inline, but trust me - it isn't.

class IDemo {     public:         virtual ~IDemo() {}         virtual void OverrideMe() = 0; };  class Parent {     public:         virtual ~Parent(); };  class Child : public Parent, public IDemo {     public:         virtual void OverrideMe()         {             //do stuff         } }; 

You don't have to include a body for the virtual destructor - it turns out some compilers have trouble optimizing an empty destructor and you're better off using the default.

like image 183
Mark Ransom Avatar answered Oct 11 '22 20:10

Mark Ransom


Make a class with pure virtual methods. Use the interface by creating another class that overrides those virtual methods.

A pure virtual method is a class method that is defined as virtual and assigned to 0.

class IDemo {     public:         virtual ~IDemo() {}         virtual void OverrideMe() = 0; };  class Child : public IDemo {     public:         virtual void OverrideMe()         {             // do stuff         } }; 
like image 30
bradtgmurray Avatar answered Oct 11 '22 22:10

bradtgmurray