Menu
CoddyTech

Overloads and Defaults

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

Go has neither ordinary overloading nor default parameter values. Use distinct function names when expressing the source operation. C++ overloads differ in parameter lists, not return type alone. Default arguments are possible, but overlapping overloads and defaults can be ambiguous.

Go

package main
import (
 "fmt"
)
func label(name string) string { return name }; func labelDefault() string { return label("guest") }
func main() {
 fmt.Println(labelDefault())
}

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

Practice on your own: Online C++ compiler