Menu
CoddyTech

Overloads and Defaults

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

JavaScript has no overloading: declaring a second function with the same name replaces the first, and one function handles every call, using default parameters (applied when an argument is missing or undefined) or by inspecting its arguments. C++ overloads are separate functions that share a name and differ in their parameter lists; the compiler picks one from the argument types at each call. Return type alone cannot distinguish overloads. Default arguments are possible too, but overlapping overloads and defaults can make a call ambiguous.

JavaScript

function label(name) {
  return "user:" + name;
}
function label(name, role = "guest") {
  return role + ":" + name;
}
console.log(label("Mira"));
console.log(label("Mira", "editor"));
console.log(label("Mira", undefined));

C++

#include <iostream>
#include <string>

std::string label(const std::string& name, const std::string& role) {
    return role + ":" + name;
}

std::string label(const std::string& name) {
    return label(name, "guest");
}

std::string label(int id) {
    return "id:" + 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 JavaScript Developers

Practice on your own: Online C++ compiler