Functions aur Overloading
C++ aapko same naam ke multiple functions declare karne deta hai, jab tak unke parameter types alag hain — ise function overloading kehte hain. Compiler call site par argument types ke basis par compile time par sahi wala pick karta hai, bina kisi runtime cost ya dispatch ke.
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int main() {
cout << add(3, 4) << endl;
cout << add(3.5, 2.5) << endl;
return 0;
}7 6
Default arguments
Ek parameter ka ek default value ho sakta hai, jo tab use hota hai jab caller woh argument omit kar de. Jab ek function ke versions ke beech sirf ek trailing value hi badalti hai, to yeh overloading ka ek simpler alternative hai.
#include <iostream>
using namespace std;
int multiply(int a, int b = 2) {
return a * b;
}
int main() {
cout << multiply(5) << endl;
cout << multiply(5, 3) << endl;
return 0;
}10 15
Ek real overload-resolution error kaisa dikhta hai
Overload resolution tabhi kaam karta hai jab compiler call ko apne normal conversion rules ke through exactly ek candidate se match kar sake — yeh chupke se kisi argument ko aisi conversion se coerce nahi karega jo implicit aur unambiguous na ho. Yeh genuinely woh hai jo g++ report karta hai jab koi overload match nahi karta — ek real run se capture kiya gaya hai, plausible dikhne ke liye likha nahi gaya:
#include <iostream>
using namespace std;
void greet(int id) {
cout << "id: " << id << endl;
}
void greet(double score) {
cout << "score: " << score << endl;
}
int main() {
greet("hello");
return 0;
}main.cpp: In function ‘int main()’:
main.cpp:13:11: error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]
13 | greet("hello");
| ^~~~~~~
| |
| const char*
main.cpp:4:16: note: initializing argument 1 of ‘void greet(int)’
4 | void greet(int id) {
| ~~~~^~Ek string literal chupke se int ya double nahi ban sakta, isliye koi bhi overload match nahi karta, aur poora program ek surprising candidate pick karne ke bajaye compile hi nahi ho paata.
Aage: control flow — if/else, for, while, aur switch.
Practice exercise
square ke do overloads likho: ek int ke liye, ek double ke liye. square(6) call karo aur result print karo.