TwinCAT Engineering Notes
← All posts

Abstract Class vs Interface in Structured Text

A comparison of abstract classes and interfaces in CoDeSys/TwinCAT, detailing inheritance, runtime type checking, and polymorphism safety.

This discussion refers specifically to CoDeSys, since behavior may differ significantly in other implementations and languages.

An interface does not support fields (variables) or logic implementation. However, if you create an abstract class without fields, where all methods and properties are also abstract, it becomes structurally very similar to an interface. Still, there are some important differences:

1️⃣ Multiple inheritance

A single class can implement multiple interfaces, but it can inherit from only one class.

2️⃣ Runtime type checking

Interfaces provide at least some runtime type-checking capabilities (e.g., __QUERYINTERFACE for interfaces that implement __SYSTEM.IQueryInterface). Classes do not provide this functionality.

3️⃣ Polymorphism options in Structured Text

To fully leverage polymorphism, you need one of these:

  • Interfaces
  • REFERENCE TO
  • POINTER TO

Among these, interfaces are the safest and most convenient. Let’s break them down:

3️⃣•1️⃣ Interface variable

  • Works like a regular object; easy to use.
  • Assignment with regular operator :=.
  • Null check with simple comparison with 0.
  • Compiler enforces type compatibility: only objects implementing the interface (or descendants) can be assigned.

3️⃣•2️⃣ REFERENCE TO class variable

  • Works like an object, but with nuances (especially properties).
  • Assignment with special REF= operator (mistaking it for := can cause subtle bugs).
  • Null check with special __ISVALIDREF operator.
  • Compiler checks types: only objects of the same type or descendants can be assigned.

3️⃣•3️⃣ POINTER TO class variable

  • Access to members requires explicit de-referencing with operator ^.
  • Assignment with regular operator :=, but obtaining object address with operator ADR.
  • Null check with simple comparison with 0.
  • Compiler does not check types — pointers can be freely reassigned, increasing the risk of errors.

✅ Conclusion

If you have an abstract class without fields, where all members are abstract, it is a perfect candidate to be replaced by an interface.

#TwinCAT #CoDeSys #StructuredText #IndustrialAutomation #OOP