Functions and overloading

Overloading, default arguments, and passing by reference.

C++ lets several functions share a name when their parameters differ. This is called overloading. Default arguments let callers leave out values that are usually the same.

C++
#include <iostream>
#include <vector>
using namespace std;

int area(int side) { return side * side; }
int area(int w, int h) { return w * h; }

double withGst(double amount, double rate = 18.0) {
  return amount + amount * rate / 100;
}

int total(const vector<int> &marks) {
  int t = 0;
  for (int m : marks) {
    t += m;
  }
  return t;
}

int main() {
  cout << area(4) << " " << area(3, 5) << "\n";
  cout << withGst(1000) << " " << withGst(1000, 5) << "\n";
  cout << total({72, 95, 60}) << "\n";
  return 0;
}
Output
16 15
1180 1050
227
ParameterWhen to use it
int xBy value: a copy. Fine for small types such as int and double
const T &xNo copy, and the function cannot change it. Use for strings, vectors and objects
T &xNo copy, and changes reach the caller

Passing a vector by value copies every element. Inside a loop over 100,000 items, that copy alone can make a coding-round solution too slow.

โ† Strings and vectorsClasses and objects โ†’