LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 3 of 27

Functions and Default Arguments

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Functions and Default Arguments · Study material

Choose the parameter type by what the function does

Small types by value, large read-only objects by const reference, objects the function must change by reference. This one rule removes most accidental copies and most "why didn't my variable change?" bugs.

#include <iostream>
#include <string>
#include <vector>

// cheap to copy → by value; big or not copyable → const&; must modify → &
int square(int x) { return x * x; }
double average(const std::vector<double>& v) {
    double s = 0;
    for (double x : v) s += x;
    return v.empty() ? 0 : s / v.size();
}
void add_suffix(std::string& s, const std::string& suffix) { s += suffix; }

int main() {
    std::string file = "report";
    add_suffix(file, ".pdf");
    std::cout << square(12) << ' ' << average({2.5, 3.5, 6.0}) << ' ' << file << '\n';
    return 0;
}

Output

144 4 report.pdf

Return a struct instead of many out-parameters

// Hard to read: which argument is input, which is output?
void parse(const std::string& s, int& day, int& month, int& year, bool& ok);

// Clear: inputs are parameters, results are the return value
struct Date { int day, month, year; };
std::optional<Date> parse(const std::string& s);

if (auto d = parse("15-08-2026")) {
    auto [day, month, year] = *d;     // structured bindings
}

Memoize expensive recursion

#include <unordered_map>

long long fib(int n) {
    static std::unordered_map<int, long long> memo;   // remembers results between calls
    if (n < 2) return n;
    if (auto it = memo.find(n); it != memo.end()) return it->second;
    return memo[n] = fib(n - 1) + fib(n - 2);
}
// fib(90) returns instantly; the naive version would make ~10^18 calls

Prefer overloading or templates to one function with a type flag

// Fragile: the caller must pass the right flag
double area(int shape, double a, double b = 0);

// Clear and checked by the compiler
double area(double radius)                  { return 3.141592653589793 * radius * radius; }
double area(double length, double width)    { return length * width; }

Good function habits

  • One function, one job – and a name that says what it does.
  • Keep functions short enough to read without scrolling.
  • Pass large objects by const&, return results by value (copy elision makes it cheap).
  • Mark functions that cannot throw noexcept and results that must be used [[nodiscard]].
  • Make pure computations constexpr.
  • Write declarations in headers and definitions in .cpp files (except inline/templates).

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links