C++ Notes
C++ Notes
Function overloading allows you to use the same function name for
different functions as long as they have different parameter lists. It helps
make your code more readable and organized.
To overload a function, you define multiple functions with the same name
but with different signatures. A function signature is the combination of
the function’s name and its parameter list.
**Note**: The return type is not part of the function signature for
overloading. Therefore, you cannot overload functions solely based on
different return types.
```cpp
#include <iostream>
return a + b;
return a + b + c;
return a + b;
int main() {
std::cout << "Add 2.5 and 3.5: " << add(2.5, 3.5) << std::endl;
return 0;
```
In this example:
```cpp
```
```cpp
```
```cpp
void show(int i, double d);
```
- **Same Number and Types but Different Return Type**: You cannot
overload functions based on return type alone.
```cpp
int getValue();
```
```cpp
```
### 8. **Conclusion**
- **Protection**: Ensures that the function does not modify the argument.
```cpp
#include <iostream>
int main() {
int num = 5;
```
In this example:
When passing large objects like strings or vectors, you often pass them by
reference to avoid copying, and you can make these references constant
to prevent modification:
```cpp
#include <iostream>
#include <vector>
int main() {
printVector(numbers);
return 0;
```
```cpp
#include <iostream>
int main() {
return 0;
```
In this example:
- When you call `greet()` without arguments, it uses `"Guest"` and `18`
as defaults.
```cpp
// Correct
// Incorrect
```cpp
```
```cpp
#include <iostream>
int main() {
return 0;
```
In this case:
### 4. **Conclusion**
```cpp
#include <iostream>
return x * x;
int main() {
int num = 5;
std::cout << "The square of " << num << " is " << square(num) <<
std::endl;
return 0;
```
In this example:
**Friend functions** are functions that are not members of a class but still
have access to the private and protected members of that class. This can
be useful for operations that need to interact closely with the internal
state of the class but don't logically belong to the class itself.
```cpp
#include <iostream>
class Box {
private:
int length;
int width;
int height;
public:
};
// Friend function definition
int main() {
return 0;
```
In this example:
### Summary
**Inline Functions**:
- Use the `inline` keyword to suggest that the compiler replace the
function call with the function code.
**Friend Functions**:
- Use the `friend` keyword to grant a non-member function access to
private and protected members of a class.
- Useful for operations that need to interact with private data but are not
logically part of the class.