tk3 (home, dev, source, bugs, help)

RPGCodeObject Oriented Coding — Polymorphism

Something you often need do in programming is express a relationship between types. Whether it be different types of numbers, jobs in an office, one class should be somehow expressed as a type of another. In object oriented programming we often express this relationship using inheritance. In inheritance, the inheriting class - or derived class - obtains all the functions and variables of the class being inherit, the base class.

In RPGCode, classes can have an unlimited number of bases and they are set like this:

class CDerived [: CBaseOne, CBaseTwo, ...]

Take this number class, for example:

// A number
class CNumber
{

	// Public visibility
	public:

		// Constructor
		method CNumber(num!)

		// Cast to numerical
		method operator!() { returnMethod(m_val!) }

		// Alter the number
		method operator=(newVal!)

	// Private visibility
	private:

		m_val!	// Value of the number

}

// CNumber - constructor
method CNumber::CNumber(num!)
{
	// Copy value to a member
	m_val! = num!
}

// CNumber - assignment operator
method CNumber::operator=(newVal!)
{
	m_val! = newVal!
}

The CNumber class provides basic functionality for a number. It does not, however, have functions specific to the type of number being manipulated. If you want to manipulate a fraction, for example, you might code a class like this:

// A fraction
class CFraction: CNumber
{

	// Public visibility
	public:

		// Constructor
		method CFraction(top!, bottom!)

		// Get the top
		method getTop() { returnMethod(m_top!) }

		// Get the bottom
		method getBottom() { returnMethod(m_bottom!) }

		// Override the = operator
		method operator=(CFraction newVal)

	// Private visibility
	private:

		m_top!	// Top of the fraction
		m_bottom!	// Bottom of the fraction

}

// CFraction - constructor
method CFraction::CFraction(top!, bottom!)
{
	// Copy params to members
	m_top! = top!
	m_bottom! = bottom!
	m_val! = m_top! / m_bottom!
}

// CFraction - assignment operator
method CFraction::operator=(CFraction newVal)
{
	m_top! = newVal->m_top!
	m_bottom! = newVal->m_bottom!
	// Also set the base class' value member
	m_val! = m_top! / m_bottom!
}

Note how the derived class can override the base class' methods. In some situations, you would expect that a method be overloaded every single time. Such relationships can be expressed using a pure virtual function. One can be defined like so:

method pureVirtual(...) = 0

No implementation for the method should be provided, and as such, a class containing even one pure virtual method cannot be created directly - only used a parameter, or inherited.

As shown, polymorphism makes it easy to express relationships between classes.


previous, forward