💻

Understanding Inline Functions in C++

Sep 9, 2024

Lecture on Inline Functions in C++

Introduction

  • Topic: Use of inline functions with classes in C++.
  • Discussion on syntax, pros, and cons of inline functions.

Class Declaration Example: Square

  • Class Name: Square
    • Private Member:
      • side (length of the side of the square)
    • Public Functions:
      • Mutator:
        • void setSide(double s) - sets the value of side.
      • Accessors:
        • double getSide() const - returns the value of side.
        • double getArea() const - calculates and returns the area of the square.

Defining Functions

  • SetSide Function:
    • Uses void return type.
    • Scope resolution operator (::) is used since function belongs to the square class.
    • Includes input validation to ensure side is positive.
      • If s > 0, update side.
      • Else, terminate the program using exit (requires including <cstdlib>).

Inline Functions

  • Key Concept: Functions are declared inline by placing them within the class declaration.
  • No inline keyword necessary.
  • Example:
    • getSide and getArea defined inline by placing their definitions within the class declaration.

Pros and Cons of Inline Functions

Pros:

  • Code Compactness:
    • Functions can be declared in one place, simplifying code structure.
  • Performance:
    • Inline expansion by the compiler leads to faster execution as it avoids the function call overhead (e.g., stack usage).

Cons:

  • Increased Program Size:
    • Inline code is replicated at each call site, potentially increasing executable size.
  • Judgment Call:
    • Decision depends on the trade-off between faster execution and larger file size.

Important Notes

  • Do not include the class name and scope resolution operator within the class declaration itself for inline functions.
  • Inline functions are ideal for simple functions where call overhead outweighs the space used by code repetition.

Conclusion

  • Inline functions offer a balance between performance improvement and code manageability at the cost of potentially larger executables.
  • Understanding inline functions enhances efficiency in C++ programming.