Documentation Center

  • Trial Software
  • Product Updates

Converting Objects to Another Class

Why Implement a Converter

You can convert an object of one class to an object of another class. A converter method has the same name as the class it converts to, such as char or double. Think of a converter method as an overloaded constructor method of another class—it takes an instance of its own class and returns an object of a different class.

Converters enable you to:

  • Use methods defined for another class

  • Ensure that expressions involving objects of mixed class types execute properly

  • Control how instances are interpreted in other contexts

Suppose you define a polynomial class. If you create a double method for the polynomial class, you can use it to call other functions that require inputs of type double.

p = polynomial(...);
dp = double(p);
roots(dp)

p is a polynomial object, double is a method of the polynomial class, and roots is a standard MATLAB® function whose input arguments are the coefficients of a polynomial.

Converters and Subscripted Assignment

When you make a subscripted assignment statement such as:

A(1) = myobj;

MATLAB compares the class of the Right-Hand-Side (RHS) variable to the class of the Left-Hand-Side (LHS) variable. If the classes are different, MATLAB attempts to convert the RHS variable to the class of the LHS variable. To do this, MATLAB first searches for a method of the RHS class that has the same name as the LHS class. Such a method is a converter method, which is similar to a typecast operation in other languages.

If the RHS class does not define a method to convert from the RHS class to the LHS class, then MATLAB software calls the LHS class constructor and passes it to the RHS variable.

For example, suppose you make the following assignments:

A(1) = objA; % Object of class ClassA
A(2) = objB; % Object of class ClassB

MATLAB attempts to call a method of ClassB named ClassA. If no such converter method exists, MATLAB software calls the ClassA constructor, passing objB as an argument. If the ClassA constructor cannot accept objB as an argument, then MATLAB returns an error.

You can create arrays of objects of different classes using cell arrays (see cell for more information on cell arrays).

Examples of Converter Methods

See the following sections for examples of converter methods:

Was this topic helpful?