Example with Multiple Inheritance and Runtime Binding
Example 8 – Multiple Inheritance and Runtime Binding
FILENAME: example8.cpp
Program:
/*
* Example illustrating the use of multiple inheritance
* to do runtime binding. Although the Math.h++ class
* library does not use any virtual functions, it is easy
* enough to implement them in a derived class by using
* multiple inheritance.
*/
#include <rw/math/mathvec.h>
#include <iostream>
/*
* This is the abstract base class where the virtual
* functions that we plan to use are declared (but
* not defined).
*/
class Printable
{
public:
virtual void print() = 0;
};
/*
* Here are two classes that inherit not only the
* abstract base class above, but also the properties of
* a Math.h++ class. The first class will inherit
* RWMathVec<DComplex>, the second RWMathVec<double>.
*/
class CVector : public RWMathVec<DComplex>,public Printable
{
public:
CVector(unsigned n, DComplex start, DComplex inc) :
RWMathVec<double>(n, start, inc) {}
virtual void print();
};
class DVector : public RWMathVec<double>, public Printable
{
public:
DVector(unsigned n, double start, double inc) :
RWMathVec<double>(n, start, inc) {}
virtual void print();
};
/*
* A little test program to illustrate.
*/
int main()
{
int type;
std::cout << "Demonstration of runtime binding.\n";
std::cout << "Type 1 for a vector of complexes;\n";
std::cout << "Type 2 for a vector of doubles: ";
std::cin >> type;
Printable* avec;
switch (type)
{
case 1 :
std::cout << "Constructing a CVector\n";
avec = new CVector(10, DComplex(0.0), DComplex(1.0) );
break;
default :
std::cout << "Constructing a DVector\n";
avec = new DVector(10, 0, 1);
}
/*
* Note that "avec" points to the *base* class Printable.
* The actual type of what it points to is unknown at
* compile time --- it depends on what the user typed
* above. Runtime binding happens for the virtual
* function print().
*/
avec->print();
}
void
CVector::print()
{
std::cout <<"Vector of complex:\n";
// Inherit the operator<<() function of RWMathVec<DComplex>:
std::cout << *this << "\n";
}
void
DVector::print()
{
std::cout <<"Vector of doubles:\n";
// Inherit the operator<<() function of RWMathVec<double>:
std::cout << *this << "\n";
}
Sample Input:
User input required.
Sample Output (shown for an input of "1"):
Demonstration of runtime binding.
Type 1 for a vector of complexes;
Type 2 for a vector of doubles: 1
Constructing a CVector
Vector of complex:
[
(0, 0) ( 1, 0) ( 2, 0) ( 3, 0) ( 4, 0)
(5, 0) ( 6, 0) ( 7, 0) ( 8, 0) ( 9, 0)
]