SECTION 2: Function Overloading, Defaults, Inline, Constants Flashcards
(8 cards)
What is function overloading in C++?
Having multiple functions with the same name but different parameter types or counts.
What are three valid ways to overload functions in C++?
Different parameter types
Different number of parameters
Different parameter sequence
void add(int a, int b);
void add(double a, double b);
void add(int a, double b);
What is a default function parameter?
A value automatically used if no argument is passed for that parameter.
void greet(string name = “User”); // greet() uses “User”
Rule for default parameters in a function?
All parameters to the right of a default argument must also have default values.
// ❌ Invalid:
int sum(int x, int y, int z = 0, int w);
// ✅ Valid:
int sum(int x, int y, int z = 0, int w = 0);
What is an inline function in C++?
A function where the compiler replaces the call with the actual code.
inline int square(int x) { return x * x; }
Difference between inline functions and macros?
Inline functions are handled by the compiler, whereas macros are handled by the preprocessor before compilation.
Inline functions are type-safe and can access class members, while macros are not type-checked and cannot access class members.
The inline keyword is used to declare inline functions, whereas macros are defined using #define.
Inline functions evaluate arguments only once, while macros may evaluate them multiple times, which can lead to unintended behavior.
What is a const parameter in C++?
A variable that cannot be modified once initialized.
void display(const int& x); // x cannot be changed inside
Rules for const variables?
Must be initialized when declared
Cannot be reassigned later
Offers optimization and safety benefits