C++ Class Methods
Lesson outline
Introduction to Class Methods
In C++, a method (member function) is a function declared within a class that operates on its objects. Member functions can access the class's private/protected data and define how objects behave.
A method can be defined directly inside the class body or declared inside the class and defined outside using the scope resolution operator (::).
Defining Methods Inside the Class
If a method is defined inside the class, it is implicitly declared with the inline specifier. This enables placing the definition in headers without violating the One Definition Rule. Note that inline does not force inlining; the optimizer decides whether to inline the call.
Defining Methods Outside the Class
For better organization, methods are often declared inside the class and defined outside using the scope resolution operator ::. The out-of-class definition must repeat the exact signature (including qualifiers like const, noexcept, reference qualifiers, etc.).
Using Parameters and Return Values
Member functions can take parameters and return values like free functions. Use const on methods that do not modify the object's state.
Const Methods and the this Pointer
Inside a const member function, the implicit this pointer is const ClassName*, so you cannot modify non-mutable data members. You can provide both const and non-const overloads when appropriate.
Static Methods
Static member functions do not have a this pointer and cannot access non-static members unless given an object/reference. They are often used for utilities related to the class.
Best Practices
- Keep each method focused on a single task for clarity.
- Mark methods
constwhen they do not modify the object's observable state. - Define short/simple methods inside the class (implicitly
inline), but move complex logic to out-of-class definitions. - Keep signatures consistent (match qualifiers in declarations/definitions).
- Group related methods and consider
staticfor utilities that do not depend on object state.