Defining and Using Interfaces

An interface is similar to a class, but all the member functions are pure virtual. Interfaces are useful for defining capabilities for diverse classes in your application. The following example shows you how to define a hypothetical interface in managed C++:

__gc __interface IStorableAsXml { void ReadFromXmlFile(String * XmlFilename); void WriteToXmlFile(String * XmlFilename); };

By convention, interface names start with the letter I, which makes it easy to differentiate between interfaces and classes.

Once you have defined the interface, you can implement it in any class that supports the functionality prescribed in the interface. The syntax for implementing an interface is the same as for extending a base class. The following example shows how to implement the IStorableAsXml interface in the SavingsAccount class:

__gc class SavingsAccount : public BankAccount, public IStorableAsXml { public: // Override functions defined in the interface void ReadFromXmlFile(String * XmlFilename){} void WriteToXmlFile(String * XmlFilename){} // Other members, as before ... };

In this example, SavingsAccount inherits from BankAccount and implements the IStorableAsXml interface. The SavingsAccount class is obliged to implement the ReadFromXmlFile and WriteToXmlFile methods.

Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
Year: 2003
Pages: 208 © 2008-2017.
If you may any questions please contact us: