What About C?


What About C++?

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 + "&nbsp;"+ LastStr +
"</B>&nbspGraduates 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();
}



OOP Demystified
OOP Demystified
ISBN: 0072253630
EAN: 2147483647
Year: 2006
Pages: 130

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net