Menu
CoddyTech

Overloads and Defaults

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

GDScript functions can declare default arguments, but there are no keyword arguments and no overloading: arguments are matched by position, and declaring a second label function in the same script is a parse error. C++ lets several functions share a name as long as their parameter lists differ, and the compiler picks one from the argument types at each call. A different return type alone is not enough. Default arguments are possible too, but overlapping overloads and defaults can make a call ambiguous.

GDScript

extends Node

func label(name: String, role: String = "guest") -> String:
	return role + ":" + name

func _ready():
	print(label("Mira"))
	print(label("Mira", "editor"))

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>

std::string label(std::string n,std::string r){return r+":"+n;}
std::string label(std::string n){return label(n,"guest");}
std::string label(int id){return "user:"+std::to_string(id);}
int main(){
std::cout<<label("Mira")<<"\n"<<label("Mira","editor")<<"\n"<<label(7)<<"\n";
}

Trace each program independently. These examples demonstrate the concept with different operations or data from the task; source and target output are not assumed to match.

challenge icon

Challenge

Easy

Input: nonnegative price and quantity. Implement both cost overloads: one argument returns price, two return price times quantity. Driver calls both.

Implement the declared API in exercise.hpp and exercise.cpp. Both files are editable; preserve the public signatures. The locked main.cpp reads stdin and calls the API directly. It also checks public API behavior independently where stated. Return values rather than printing inside the API. Integer inputs and results fit signed int; text is ASCII unless stated otherwise.

Try it yourself

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int p,q;in>>p>>q;std::cout<<cost(p)<<" "<<cost(p,q)<<"\n";
}
quiz iconTest yourself

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

All lessons in C++ for GDScript Developers

Practice on your own: Online C++ compiler