TwinCAT Engineering Notes
← All posts

Calling Virtual Members from FB_Init in TwinCAT

What happens when you call a virtual method or property from FB_Init in TwinCAT / CoDeSys? Exploring polymorphic constructor behavior and uninitialized fields.

Imagine the following scenario: you have a base function block whose constructor (FB_Init) calls a virtual member (a method or property). That member is overridden in a derived block.

What will happen when you instantiate the derived block?

  1. The base block’s method is called (like in C++).
  2. The derived block’s method is called (like in C# / Java).
  3. The compiler issues an error and prevents building the project.

💡 The Correct Answer: 2

In TwinCAT / CoDeSys, the call is a “true” virtual call — meaning the overridden implementation in the derived block is invoked.

However, you must be extremely cautious. When the base block’s FB_Init is executing, the derived block has not yet finished being constructed:

  • Explicitly defined default values for the derived block’s fields have not yet been assigned;
  • The derived block’s FB_Init has not yet been executed;
  • As a result, you risk encountering uninitialized data, empty values, or unpredictable behavior.

🧩 Example Breakdown

Take a look at the example shown in the screenshot below:

  • We have a base abstract class Device with an internal Name field and an abstract ClassName property.
  • In Device.FB_Init, there is an input parameter name. If name is passed as an empty string, the base constructor assigns Name := ClassName; to ensure the device name is not empty.

Whether this algorithm works correctly depends entirely on how you implement the ClassName property in derived classes:

1️⃣ Derived Class DigitalInput — Broken Approach ❌

DigitalInput defines an internal field _ClassName with a default value:

_ClassName : STRING := 'DigitalInput';

The overridden ClassName property returns this internal field:

ClassName := _ClassName;

This will not work as expected: while the base FB_Init is running, the derived class fields have not yet received their default values, so _ClassName is still an empty string (''). Consequently, Name ends up being empty!

2️⃣ Derived Class DigitalOutput — Working Approach ✅

In DigitalOutput, the overridden ClassName property directly returns a string literal:

ClassName := 'DigitalOutput';

This approach works correctly because returning a literal does not depend on the uninitialized state of the derived block’s instance variables.

3️⃣ Derived Class with VAR_STAT — Working Approach ✅

What if you use a static variable (VAR_STAT) instead?

In TwinCAT / CoDeSys, variables declared in VAR_STAT are initialized by the runtime before any FB_Init constructors run — even before the initialization of the base class (predecessor)!

Therefore, this pattern works reliably: by the time the base block’s constructor executes, the derived block’s static variable is already initialized:

FUNCTION_BLOCK ABSTRACT Device
    VAR_OUTPUT
        Name : STRING;
    END_VAR

    METHOD FB_init : BOOL
        VAR_INPUT
            bInitRetains : BOOL; // TRUE: the retain variables are initialized (reset warm / reset cold)
            bInCopyCode  : BOOL; // TRUE: the instance will be copied to the copy code afterward (online change)
            name         : STRING;
        END_VAR
        
        IF name <> '' THEN
            THIS^.Name := name;
        ELSE
            THIS^.Name := ClassName;
        END_IF        
    END_METHOD

    {attribute 'monitoring' := 'call'}
    PROPERTY ABSTRACT ClassName : REFERENCE TO STRING
        GET
        END_GET
    END_PROPERTY
END_FUNCTION_BLOCK

FUNCTION_BLOCK DigitalInput EXTENDS Device
    VAR_STAT
        _ClassName : STRING := __POUNAME();    
    END_VAR
    
    {attribute 'monitoring' := 'call'}
    PROPERTY ClassName : REFERENCE TO STRING
        GET
            ClassName REF= _ClassName;
        END_GET
    END_PROPERTY
END_FUNCTION_BLOCK

In this example:

  • _ClassName is placed in VAR_STAT and initialized using the __POUNAME() operator, which automatically resolves to the POU name ('DigitalInput');
  • Because VAR_STAT variables are initialized prior to the base FB_Init invocation, THIS^.Name := ClassName; immediately receives the correct value;
  • Returning REFERENCE TO STRING avoids redundant string copying overhead.

⚠️ Takeaways

If you find yourself needing to invoke virtual members from FB_Init:

  • Keep the object lifecycle in mind: the derived block’s state is completely uninitialized during base constructor execution.
  • Never rely on instance variables or default-initialized fields of the derived class inside those virtual members.
  • Use literals, constants, static variables (VAR_STAT), or pass explicit configuration via extended FB_Init parameters instead.

Calling virtual members from FB_Init

#TwinCAT #CoDeSys #OOP #StructuredText #IndustrialAutomation #FB_Init