As stated at the beginning of this chapter, C++ does not provide syntactical support for interfaces. However, C++ does provide support for multiple inheritance. Earlier on we described how an interface is very similar to a class with all abstract methods . The problem in Java and C# is a lack of multiple inheritance, which means we can t use this type of class and therefore have to use interfaces.
In C++, thanks to multiple inheritance, we can do something very similar by using a class with all abstract (or pure-virtual) methods. Consider the following C++ class:
class HTMLSource
{
public:
virtual string GetHTML() const = 0;
};
Here we have a class with a single pure-virtual function, much like the Java and C# interfaces from earlier. Now, we declare a Student class, derived from the Person class and the HTMLSource class, and provide the GetHTML method:
class Student: public Person, HTMLSource
{
public:
string GetHTML()
{
return "<B>" + FirstStr + " "+ LastStr +
"</B> Graduates in " + GraduationYear;
}
// Portions of class removed for readability
};
As in Java and C#, we write a function in C++ that takes an HTMLSource object as a parameter and can accept any class with HTMLSource somewhere in its ancestry:
void ShowHTML( const HTMLSource& Src )
{
cout << Src.GetHTML();
}