In object-oriented programming, a method is a function that is a member of a class, invoked through an object with the dot operator or the arrow operator (for object pointers).
The this
keyword in C++ (analogous to self
) is a constant pointer to the object itself. This is useful when we need to refer to the object within methods.
Note that only methods can access private
members of the class. Functions outside of the class can’t! But to bypass this restriction we can set some functions as friend functions, where it can access private members and the LHS can be of a type that’s not the class. But they’re not members of the class and must be implemented outside. On a class level, methods of the same class are able to access each other’s private attributes.
For a multi-line method call, we go from left to right. This isn’t true for overloaded operators.
Common types and concepts
In Rust
We add methods to structs with:
Associated functions don’t have self
as the first parameter (and thus aren’t methods). They’re mainly used as constructors to return -> Self
.