July 02, 2007
Simulating Polymorphic Operators in C++
Version 1: Auxiliary Methods
The first and simplest version accomplishes the polymorphic behavior by adding extra virtual methods to each class. While the operators are nonmember functions, these new items are methods and can be polymorphic. So my insertion operator calls a polymorphic virtual method from the class and I let the compiler do the heavy lifting. Compilers typically build a table of function pointers called a "virtual function table" (vtable) to help resolve the call to a virtual method. Each class with a virtual method has memory allocated for a vtable. In addition, every object or instance of a class with virtual methods has a pointer to the vtable. Therefore, the space required for this version is the memory for the class's vtable plus memory for a pointer in each and every object. Listing One presents this version of the Employee example.
class Employee
{
public:
friend ostream& operator<<(ostream& os, const Employee & aEmployee);
virtual ostream& print(ostream& os) const;
};
class Manager : public Employee
{
public:
friend ostream& operator<<(ostream& os, const Manager & aManager);
virtual ostream& print(ostream& os) const;
};
ostream& Employee::print(ostream& os) const
{
// code to print the Employee class
return os;
}
ostream& operator<<(ostream& os, const Employee & aEmployee)
{
return aEmployee.print(os);
}
ostream& Manager::print(ostream& os) const
{
Employee::print(os);
// code to print the Manager class
return os;
}
ostream& operator<<(ostream& os, const
Manager & aManager)
{
return aManager.print(os);
}
Listing One
Previous Page |
1 Simulating Polymorphic Operators in C++
|
2 Version 1: Auxiliary Methods
|
3 Version 2: The dynamic_cast Operator
|
4 Version 3: An Enumerated Type
|
5 How Do They Compare?
Next Page