I am trying to generate code using MATLAB coder from source code that utilizes polymorphism. I have created an example in both MATLAB and C++, with a class hierarchy in which classes "MyClassOne" and "MyClassTwo" inherit from an abstract class "MyAbstractClass", which contains the abstract method "PolymorphFunction".
The following code can be successfully written and compiled in both MATLAB and C++:
switch operationType
case OperationType.MyOperationOne
myOperator = MyClassOne(x);
case OperationType.MyOperationTwo
myOperator = myClassTwo(x);
end
myOperator.PolymorphFunction(y);
However, trying to generate code creates an error: 
Code generation does not support changing types through assignment.
However, the type does not change, it is just determined by the switch statement. Given that C++ supports polymorphism and templates, why does MATLAB Coder not support this behavior?
 

 Respuesta aceptada

MathWorks Support Team
MathWorks Support Team el 24 de Sept. de 2026 a las 0:00
This is expected behavior, as MATLAB Coder does not currently support polymorphism. To work around the behavior, perform the follow-up operation on the object from within the switch case as well, e.g.: 
switch operationType
case MyOperationType.MyOperationOne
myOperator = MyClassOne(x);
myOperator.PolymorphFunction(y);
case MyOperationType.MyOperationTwo
myOperator = MyClassTwo(x);
myOperator.PolymorphFunction(y);
end

Más respuestas (0)

Categorías

Más información sobre Simulink Coder en Centro de ayuda y File Exchange.

Productos

Versión

R2017b

Preguntada:

el 24 de Sept. de 2026 a las 0:00

Respondida:

el 24 de Sept. de 2026 a las 12:31

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by