Yes, a friend function can be declared inline. Declaring a function inline suggests to the compiler to insert the function's code directly at the point of call, which can improve performance by avoiding function call overhead.
An inline friend function is defined inside the class declaration:
#include <iostream>
class MyClass {
friend void showValue(MyClass &obj) {
std::cout << "Value: " << obj.value << "\n";
}
private:
int value{42};
};
int main() {
MyClass obj;
showValue(obj);
}
Value: 42
In this example, showValue()
is an inline friend function defined within the class. It has access to the private member value
.
inline
keyword is a suggestion to the compiler. The compiler can choose to ignore it if inlining is not deemed beneficial.Here’s an example with multiple inline friend functions:
#include <iostream>
class Rectangle {
friend int calculateArea(Rectangle &rect) {
return rect.width * rect.height;
}
friend void displayDimensions(Rectangle &rect) {
std::cout << "\nWidth: " << rect.width
<< ", Height: " << rect.height;
}
public:
Rectangle(int w, int h) : width{w}, height{h} {}
private:
int width, height;
};
int main() {
Rectangle rect(10, 20);
std::cout << "Area: " << calculateArea(rect);
displayDimensions(rect);
}
Area: 200
Width: 10, Height: 20
Here, calculateArea()
and displayDimensions()
are both inline friend functions. They provide efficient access to the Rectangle
's private members.
Inline friend functions can optimize performance by reducing function call overhead and can improve readability by keeping related code together. However, use inlining judiciously to avoid potential increases in code size and complications in debugging.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the friend
keyword, which allows classes to give other objects and functions enhanced access to its members