C++ ยท Chapter 32 of 49

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.

Example 1 (cpp)
class Counter {
public:
    int count = 0;
    void increment() { count++; }
};
int main() {
    Counter c;
    c.increment();
    c.increment();
    std::cout << c.count;
}
Output
2

Calling 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.
๐Ÿ’ก Note: Marking read-only methods const lets them be called on const references, which is important for passing objects efficiently.

๐Ÿ“ Quick Quiz

1. Which operator is used to define a method outside the class?

2. What does a const method promise?

3. Methods inside a class can access: