Menu
CoddyTech

Constructor (_init)

Part of the Object Oriented Programming section of Coddy's GDScript journey. Lesson 7 of 65.

Setting every property after new() takes several lines, and it is easy to forget one. A constructor sets an object up as it is created. In GDScript the constructor is the method _init():

# book.gd
class_name Book
extends RefCounted

var title: String
var author: String
var pages: int

func _init(book_title: String, book_author: String, page_count: int) -> void:
	title = book_title
	author = book_author
	pages = page_count

The arguments you pass to new() go to _init(), which runs automatically before new() returns the object:

var dune := Book.new("Dune", "Frank Herbert", 412)
print(dune.title) # Dune
print(dune.pages) # 412

When _init() has parameters, new() must pass them: Book.new() with no arguments is an error reported before the program runs. A parameter with a default value is optional:

func _init(book_title: String, book_author: String = "Unknown") -> void:

With this constructor, Book.new("Notes") creates a book whose author is "Unknown".

The parameter names above differ from the property names. If they were the same, you would write self.title = title, as in the lesson on self.

challenge icon

Challenge

Easy

Complete the class Book in book.gd:

  • the constructor _init(book_title, book_author, page_count) stores its arguments in the properties title, author and pages
  • describe() returns 'TITLE' by AUTHOR, PAGES pages, with the title in single quotes

The supplied code reads how many books follow, then one line per book with the title, author and page count separated by ;. It creates each book with Book.new(), prints describe(), and finally prints the total of the pages properties. For the line Dune;Frank Herbert;412 it prints:

'Dune' by Frank Herbert, 412 pages
Total pages: 412

Your code goes in book.gd. main.gd holds the supplied input/output code and cannot be edited.

Try it yourself

extends Node

func _ready():
	# Supplied input/output code: keep it as it is
	var count := int(OS.read_string_from_stdin())
	var total := 0
	for i in count:
		var parts := OS.read_string_from_stdin().split(";")
		var book := Book.new(parts[0], parts[1], int(parts[2]))
		print(book.describe())
		total += book.pages
	print("Total pages: %d" % total)
quiz iconTest yourself

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

All lessons in Object Oriented Programming

Practice on your own: Online GDScript compiler