Menu
CoddyTech

Dynamic Dispatch

Lesson 28 of 48 in Coddy's GDScript for C++ Developers course.

A C++ abstract base class with virtual methods can define a runtime interface; pure virtual requirements must be implemented before constructing a concrete instance. GDScript Object.call instead looks up a named method dynamically, while typed script references express inheritance relationships. A dynamic call still needs a real compatible operation. Use has_method for optional capabilities and enforce required contracts explicitly. Consumers must call the supplied collaborator, not silently substitute a preferred implementation. The example asks a bell to speak.

Complete C++ comparison. Save the listed files together and compile the .cpp files with C++20; main is the entry point.

C++ file speaker.hpp:

#pragma once
#include <string>
struct Speaker { virtual ~Speaker()=default; virtual std::string speak() const=0; };

C++ file bell.hpp:

#pragma once
#include "speaker.hpp"
struct Bell:Speaker { std::string speak() const override { return "ding"; } };

C++ file main.cpp:

#include <iostream>
#include "bell.hpp"
int main() { Bell bell; const Speaker &s=bell; std::cout << s.speak() << '\n'; }

C++ output:

ding

GDScript example file demo_bell.gd:

class_name DemoBell
extends RefCounted
func speak() -> String:
	return "ding"

GDScript example file main.gd:

extends Node

func _ready() -> void:
	var bell: DemoBell = DemoBell.new()
	print(bell.call("speak"))

GDScript output:

ding
challenge icon

Challenge

Easy

FeeReader.total(policy:RefCounted,units:int)->int must invoke the supplied policy cost method. FlatPolicy.cost returns 5 regardless of units. Solve uses FlatPolicy. The driver also supplies a different compatible policy.

Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.

Your code goes in fee_reader.gd, flat_policy.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.

Try it yourself

extends Node

class ProbePolicy extends RefCounted:
	func cost(units: int) -> int:
		return units * 4 + 1

func contract_ok(data: Array) -> bool:
	if FlatPolicy.new().cost(9) != 5 or FeeReader.total(ProbePolicy.new(),4) != 17: return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for C++ Developers

Practice on your own: Online GDScript compiler