Interfaces Explained


In the last hour, you worked with collections, and the term interface was used often without any deep discussion on what an interface is or does. An interface provides a contract between itself and the object that will implement it. It's similar to the concept of class declaration and class definition. In other words, if you create a class declaration within a header file but do not implement any of the functions within the source file (.cpp file) and then try to compile, the compiler will inform you that the member function definitions are missing. More specifically, you told the compiler you were going to make a class with certain member functions but then failed to do so.

Similarly, if you create a class and say that it implements a certain interface but doesn't implement any of the interface methods or properties, you've broken that contract. If a class implements an interface, it must implement all the methods and properties of that interface.

So, what makes an interface different from a regular class declaration? First of all, an interface doesn't have to be implemented by a class. A structure (struct) can just as well implement an interface. Second, an interface is meant to be used by different programming languages. This is why you see an interface within the .NET Framework documentation that can be used with C#, Visual Basic, or C++. This being the case, an interface must support data types that can be used (or at least mapped by the compiler) with any programming language that supports interfaces. Lastly, a separation exists between the interface and the implementation. For instance, when a class is declared, there is one implementation for it. When an interface is created, there can be different implementations for that interface. You saw this during the last hour. There is a single interface, ICollection, but several implementations, as seen in all the different collection classes that implement that interface.


Sams Teach Yourself Visual C++. NET in 24 Hours
Sams Teach Yourself Visual C++.NET in 24 Hours
ISBN: 0672323230
EAN: 2147483647
Year: 2002
Pages: 237

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: