Lesson 133 +10 XP

Class Methods

Class Methods

A method is a function inside a class. It can use the data members of that class, which makes it the natural home for behaviors like setSpeed() or showBrand().

Defining a method inside the class

class Car {
public:
  string brand;
  int year;
  void show() {
    cout << brand << " " << year;
  }
};

The method body sits inside the class body, so it sees the class members directly.

Defining a method outside the class

For longer methods it stays cleaner to keep the body outside. You declare the method inside the class, then define it outside with the scope resolution operator :::

class Car {
public:
  void show();
};

void Car::show() {
  cout << "Hello";
}

Writing void Car::show() tells the compiler which class show belongs to. Without it, the compiler thinks you're defining a random free function.

Calling a method

Call an object's method with the dot operator:

Car myCar;
myCar.show();

TL;DR

  • A method is a function that belongs to a class.
  • Define it inside the class, or outside with ClassName::.
  • :: is the scope resolution operator that binds a method to its class.
  • Call with the dot operator: object.method();.
  • Methods can touch the object's own members without extra arguments.