Menu
CoddyTech

Overloads and Defaults

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

Ruby has no overloading: a second def with the same name replaces the first, so one method must handle every call shape with default values such as role = "guest" or keyword arguments. C++ keeps several functions with one name and picks one from the arguments at compile time. C++ overloads differ in parameter lists, not return type alone. Default arguments are possible, but overlapping overloads and defaults can be ambiguous.

Ruby

def label(name)
  "guest:" + name
end

def label(name, role)
  role + ":" + name
end

puts label("Mira", "editor")
begin
  puts label("Mira")
rescue ArgumentError => e
  puts e.message
end

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 Ruby Developers

Practice on your own: Online C++ compiler