C++ - Methods & Overloading
Overview
Estimated time: 45–65 minutes
Write clear member functions and apply overloading. Learn const-correctness for methods, function overloading, and a taste of operator overloading with best practices.
Learning Objectives
- Define const and non-const member functions appropriately.
- Use function overloading and understand overload resolution basics.
- Implement simple operator overloads safely (e.g., operator+).
Prerequisites
Const methods and overloads
#include <iostream>
class Box {
int w{0}, h{0};
public:
Box() = default;
Box(int w, int h): w{w}, h{h} {}
int area() const { return w*h; }
void resize(int nw, int nh){ w=nw; h=nh; }
};
int main(){
const Box a{3,4};
std::cout << a.area() << "\n"; // OK: const method
Box b{2,2};
b.resize(5,5);
std::cout << b.area() << "\n";
}
Expected Output:
12
25
Function overloading
#include <iostream>
int add(int a, int b){ return a+b; }
double add(double a, double b){ return a+b; }
int main(){
std::cout << add(2,3) << "\n"; // calls int version
std::cout << add(2.5,3.1) << "\n"; // calls double version
}
Expected Output:
5
5.6
Operator overloading (value semantics)
#include <iostream>
struct Vec2 {
int x{0}, y{0};
};
Vec2 operator+(const Vec2& a, const Vec2& b){ return {a.x+b.x, a.y+b.y}; }
std::ostream& operator<<(std::ostream& os, const Vec2& v){ return os << "(" << v.x << "," << v.y << ")"; }
int main(){
Vec2 a{1,2}, b{3,4};
std::cout << (a+b) << "\n";
}
Expected Output: (4,6)
Static methods and factories
#include <memory>
class Logger {
public:
static Logger createStdout();
};
Const vs non-const overloads
struct Buffer {
int data[2]{1,2};
int& operator[](int i){ return data[i]; }
const int& operator[](int i) const { return data[i]; }
};
Advanced: ref-qualified methods (C++11+)
#include <string>
struct S {
std::string str;
std::string& value() & { return str; } // lvalue object
std::string value() && { return std::move(str); } // rvalue object
};
Common Pitfalls
- Overloading operators that break expected semantics (e.g., making operator== do non-equality).
- Forgetting const on operator overloads and accessors.
Checks for Understanding
- When should a member function be marked const?
- What determines which overload is called?
Show answers
- When it does not modify observable state of the object.
- Overload resolution considers argument types, conversions, and best match rules.
Exercises
- Add operator- to Vec2 and test it; add a const method lengthSquared() and print it.
- Create overloaded print functions that accept int, double, and std::string; verify which is called in mixed expressions.