C++ Interfaces

An interface is a description of what member functions must a class, which inherits this interface, implement. In other words, an interface describes behavior of the class. You can imagine an interface as a list of functions that must be implemented by a class.

An interface is created by using __interface keyword:

__interface InterfaceName
{
	//group of functions declarations
}

A good style is to start the name of interface with I followed by the name of interface.

An interface can inherit functions from one or more base interface. It can contain only public member functions. In contrast, it cannot contain constructor, destructor, data members, and static member functions.

You can create an interface as an abstract class with public pure virtual functions that will follow these rules. However, __interface keyword enforces these properties.

Look on the example of interface:

__interface IPrintable
{
	void Print();
	void PrintBase(int);
};

This is definition of IPrintable interface. It consists of two functions, Print() and PrintBase(int). If you want to inherit an interface in your class, you have to implement these functions inside of this class. If you do not implement functions from inherited interface, your class will become abstract.

For example, we will create a class that will hold a set of three numbers:

class SomeData
{
public:
	SomeData(int x, int y, int z)
	{
		X = x;
		Y = y;
		Z = z;
	}
private:
	int X;
	int Y;
	int Z;
};

If we want to implement IPrintable interface in class SomeData, we have to modify class declaration:

class SomeData : public IPrintable

Now you have to implement functions from IPrintable interface in SomeData class:

void Print()
{
	cout << "X = " << X << endl;
	cout << "Y = " << Y << endl;
	cout << "Z = " << Z << endl;
}
void PrintBase(int base = 10)
{
	if (base != 10 || base != 8 || base != 2)
		base = 10;
	cout << setbase(base);
	cout << "X = " << X << endl;
	cout << "Y = " << Y << endl;
	cout << "Z = " << Z << endl;
	cout << setbase(10);
}

You can do the same interface using an abstract class. IPrintable interface will look as an abstract class in the following way:

class IPrintable
{
public:
	virtual void print() = 0;
	virtual void printBase(int) = 0;
	~IPrintable();
};

It is very important to add virtual destructor to the abstract class. If you do not add virtual destructor, the destructor of inherited class will never be called, even when the object is destroyed.

Translate ยป