Menu
CoddyTech

Overloads and Defaults

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

Kotlin supports overloads and default parameter values, and named arguments let a call set any parameter in any order. C++ has overloads and defaults too, but no named arguments, so only trailing defaults can be left out. C++ overloads differ in parameter lists, not return type alone. Default arguments are possible, but overlapping overloads and defaults can be ambiguous.

Kotlin

fun label(name: String, role: String = "guest") = "$role:$name"

fun main() {
    println(label("Mira"))
    println(label(role = "editor", name = "Ada"))
}

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");}
int main(){
std::cout<<label("Mira")<<"\n"<<label("Mira","editor")<<"\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 Kotlin Developers

Practice on your own: Online C++ compiler