C++ Class Methods
Methods are functions defined inside a class that operate on that object's data. They can be defined inline inside the class body, or declared inside the class and defined outside using the scope resolution operator `::`.
Methods that don't modify the object's state should be marked `const`, which both documents intent and lets you call them on const objects.
Defining methods outside the class
`void Car::honk() { ... }` defines a method declared in the class body elsewhere, useful for separating interface (header) from implementation.
const methods
`int getSpeed() const { return speed; }` promises not to modify member variables, enforced by the compiler.
class Counter {
public:
int count = 0;
void increment() { count++; }
};
int main() {
Counter c;
c.increment();
c.increment();
std::cout << c.count;
}2Calling increment() twice mutates the object's count field.
Key points
- Methods are functions defined inside (or for) a class.
- Use ClassName::method to define outside the class body.
- const methods promise not to modify member data.
- Methods access the object's own members directly by name.
