Constructors and destructors
Demonstrates construction and destruction timing; Go and Rust replace language-level constructors with New/new convention functions.
C C23
#include <stdio.h>
typedef struct {
char name[16];
} Logger;
void logger_init(Logger *l, const char *name) { // equivalent to __construct
snprintf(l->name, sizeof(l->name), "%s", name);
printf("Construct: %s\n", l->name);
}
void logger_destroy(Logger *l) { // equivalent to __destruct: must be called explicitly
printf("Destroy: %s\n", l->name);
}
int main(void) {
Logger l;
logger_init(&l, "app");
printf("In use\n");
logger_destroy(&l); // C has no reference counting; unset is equivalent to an explicit destructor call
printf("Script end");
return 0;
}
Construct: app In use Destroy: app Script end
C++ C++26
#include <iostream>
#include <string>
#include <utility>
class Logger {
std::string name;
public:
Logger(std::string n) : name(std::move(n)) { // constructor + initializer list
std::cout << "Construct: " << name << "\n";
}
~Logger() { // destructor: runs on scope exit (RAII)
std::cout << "Destroy: " << name << "\n";
}
};
int main() {
{
Logger l("app");
std::cout << "In use\n";
} // scope ends, destructor runs automatically
std::cout << "End\n";
return 0;
}
Construct: app In use Destroy: app End
C# v11.0.100
using (var l = new Logger("app")) { // the using block calls Dispose at its end
Console.WriteLine("In use");
}
Console.WriteLine("End");
// note: C# also has finalizers, but they are triggered non-deterministically by the GC; the IDisposable pattern is idiomatic
class Logger : IDisposable {
private readonly string name;
public Logger(string name) { // constructor
this.name = name;
Console.WriteLine($"Construct: {name}");
}
public void Dispose() => Console.WriteLine($"Dispose: {name}"); // deterministic resource cleanup
}
Construct: app In use Dispose: app End
Go v1.27.4
package main
import "fmt"
type Logger struct {
name string
}
// Go has no language-level constructor; convention is a package-level NewXxx function returning an initialized instance
func NewLogger(name string) *Logger {
fmt.Printf("Construct: %s\n", name)
return &Logger{name: name}
}
func main() {
l := NewLogger("app")
fmt.Println("In use:", l.name)
// no destructor; if cleanup is needed, the convention is an explicit Close() method paired with defer
}
Construct: app In use: app
Java v27.0.1
public class Main {
static class Logger {
private String name;
Logger(String name) { // constructor: same name as the class, no return value
this.name = name;
System.out.println("Construct: " + name);
}
}
public static void main(String[] args) {
Logger l = new Logger("app");
System.out.println("In use");
// Java has no destructor; finalize is deprecated, use try-with-resources for cleanup
}
}
Construct: app In use
JavaScript v26.13.1
class Logger {
constructor(name) { // ES6 class constructor
this.name = name;
console.log(`Construct: ${name}`);
}
}
const l = new Logger("app");
console.log("In use");
// JS has no destructor; objects are reclaimed by the garbage collector
Construct: app In use
PHP v8.6.0
class Logger {
private string $name;
public function __construct(string $name) {
$this->name = $name;
echo "Construct: $name\n";
}
public function __destruct() {
echo "Destroy: {$this->name}\n"; // fires on unset or at script end
}
}
$l = new Logger("app");
echo "In use\n";
unset($l); // reference count hits zero, destructor fires immediately
echo "Script end\n";
Construct: app In use Destroy: app Script end
Python v3.15.2
class Logger:
def __init__(self, name): # initializer (the object already exists; it only assigns fields)
print(f"Init: {name}")
self.name = name
l = Logger("app")
print("In use")
# Python has no deterministic destruction: __del__ timing is unpredictable,
# release resources with the with statement (context manager); do not rely on __del__
Init: app In use
Rust v1.99.1
struct Logger {
name: String,
}
impl Logger {
// Rust has no language-level constructor; convention is a new associated function returning an instance
fn new(name: &str) -> Logger {
println!("Construct: {}", name);
Logger { name: name.to_string() }
}
}
fn main() {
let l = Logger::new("app");
println!("In use: {}", l.name);
// implementing the Drop trait runs cleanup deterministically at scope exit
}
Construct: app In use: app
TypeScript v26.13.1
class Logger {
private name: string;
constructor(name: string) {
this.name = name;
console.log(`Construct: ${name}`);
}
}
const l = new Logger("app");
console.log("In use");
// TS/JS has no destructor; objects are reclaimed by the garbage collector
Construct: app In use
Language differences
C: pairs init/cleanup functions to mimic constructor and destructor; they must be called explicitly in pairs (no reference counting).
C++: a destructor runs deterministically at scope exit (the RAII idiom).
C#: pairs the constructor with IDisposable for deterministic cleanup (using disposes at block end, the destructor equivalent); finalizers run non-deterministically under the GC.
Go: no language-level constructor — conventionally a NewXxx() function; the convention is a Close() method paired with defer.
Java: a constructor named after the class; only garbage collection and no destructor (the finalize method is deprecated).
JavaScript: constructor; only garbage collection, no destructor.
PHP: the constructor is __construct; the destructor __destruct fires on unset or at script end (the example shows immediate destruction on unset).
Python: the constructor is __init__; __del__ timing is unpredictable, so resources are released with the with statement; also, the instance is actually created by __new__, and __init__ only initializes it.
Rust: no language-level constructor — conventionally Xxx::new(); implements the Drop trait for deterministic execution on scope exit.