Inline Functions
Creating new functions is not always good. It is slow, not optimized for the CPU cache. Sometimes, functions are good for readability. But if the calculations are simple, the overheads of calling the functions are burdensome. So that's why you should use inline functions.
// Member Inline Function
// Animal.h
class Animal
{
public:
Animal(int age);
inline int GetAge() const;
}
int Animal::GetAge() const;
{
return mAge;
}
// Main.cpp
Cat* myCat = new Cat(2, "Coco");
int age = myCat->GetAge(); // int age = myCat.mAge; (while compiling)
// non-Member Inline Function
// Math.h
inline int Square(int member)
{
return number * number;
}
// Main.cpp
int main()
{
int number = 2;
int result = Square(number); // int result = number * number;
return 0;
}
Inline Functions vs. #define
It is similar to MACRO or copy&paste. MACRO is hard to debug. Its function name is not shown at the call stack, and it can't set breakpoints. And also it doesn't conform to scope. So as possible as you can, use the inline functions.
What the Compiler Does
1. inline keywords are just hints.
Inline functions might not be used as inline functions. Or even if the programmer didn't meant to make an inline function, the compiler sometimes make the function works as an inline function.
2. The implementation of the inline functions must be in the header file.
It's because the compiler needs to read the implementation. Each cpp file is compiled separately.
Notes
Inline functions are appropriate for simple functions such as getter or setter. They may cause an increase of the size of exe file. So don't ubuse.
'College Study > C++ (ENG)' 카테고리의 다른 글
[C++] Exception (ENG) (0) | 2022.01.02 |
---|---|
[C++] Static Keyword (ENG) (0) | 2022.01.02 |
[C++] Casting (ENG) (0) | 2022.01.02 |
[C++] Object-Oriented Programming: Interface (ENG) (0) | 2022.01.02 |
[C++] Object-Oriented Programming: Polymorphism (ENG) (0) | 2022.01.02 |
댓글