Aussie AI

Specialize inherited member functions

  • Book Excerpt from "Generative AI in C++"
  • by David Spuler, Ph.D.

Specialize inherited member functions

In an inheritance hierarchy, the derived class is a specialized version of the base class. This means that member functions inherited from the base class can often be rewritten more efficiently to make use of the known special features of the derived class objects.

Example: Triangular Matrix Algebra. As an example, consider a class “UTMatrix” (upper triangular matrix) which is derived from class “Matrix” and represents matrices where all elements below the main diagonal are zero.

The general matrix “add” function of the Matrix class is inherited by the UTMatrix class, and it will work correctly. However, this inherited function is inefficient and it is more efficient to add a new member function to the UTMatrix class to add two upper triangular matrices avoiding all additions involving elements below the diagonal (because they are known to be zero).

In fact, it is also more efficient to write special functions to add ordinary matrices to upper triangular matrices. The computation of the determinant of a triangular matrix is also more efficient than that for a general square matrix, so this member function should also be rewritten in the UTMatrix class.

Example: Complex Numbers. As another example, consider a class “Imaginary” (imaginary numbers) derived from another class “Complex” (complex numbers). For all operations involving Imaginary objects, it is certain that the real part of the complex number is zero. Hence, it is more efficient to rewrite all inherited operations that use the real part of a Complex object, such as: addition, multiplication, norm, etc.

The main disadvantage of specializing member functions is that the code reuse advantage of inheritance is negated; more programmer time must be spent on recoding the specialized member functions. Other disadvantages are the increased probability of error, most special cases to test, and an increase in executable code size.

 

Next:

Up: Table of Contents

Buy: Generative AI in C++: Coding Transformers and LLMs

Generative AI in C++ The new AI programming book by Aussie AI co-founders:
  • AI coding in C++
  • Transformer engine speedups
  • LLM models
  • Phone and desktop AI
  • Code examples
  • Research citations

Get your copy from Amazon: Generative AI in C++