Topic 57 of 83
Compile-time Poly
Overview
Compile-time (Static) polymorphism is resolved by the compiler before the program runs. It is achieved through Function Overloading and Operator Overloading.
Syntax
cpp
// Function Overloading
void print(int i);
void print(string s);
// Operator Overloading (e.g., teaching '+' how to add two custom objects)
class Vector2D {
public:
int x, y;
// Overloading the + operator
Vector2D operator+(const Vector2D& other) {
Vector2D result;
result.x = this->x + other.x;
result.y = this->y + other.y;
return result;
}
};Common Pitfalls
- You cannot overload certain operators in C++, such as `::` (scope), `.` (member access), and `?:` (ternary).
Interview Tips
- Operator overloading should be intuitive. Do not overload `+` to perform subtraction, as it ruins code readability.
Real-World Example
Adding two Point objects together naturally using `+`.
example
cpp
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
Point(int x, int y) : x(x), y(y) {}
Point operator+(const Point& p) {
return Point(x + p.x, y + p.y);
}
};
int main() {
Point p1(1, 2);
Point p2(3, 4);
Point p3 = p1 + p2; // Clean and intuitive!
cout << "p3: " << p3.x << ", " << p3.y << endl;
return 0;
}