C++ Class Methods

Methods are functions that belong to a class. They give your objects behavior, letting them do things with the data they hold. You can define a method right inside the class or declare it inside and define it outside.

An attribute stores what an object knows; a method describes what an object can do. Because a method lives inside the class, it can use the object's attributes directly by name without any special prefix.

Methods Defined Inside the Class

The simplest way to add behavior is to write the full function inside the class body. This is convenient for short methods.

An inside method

#include <iostream>
using namespace std;

class Rectangle {
  public:
    int width;
    int height;

    int area() {           // method defined inside
      return width * height;
    }
};

int main() {
  Rectangle r;
  r.width = 5;
  r.height = 3;
  cout << "Area: " << r.area();   // call the method
  return 0;
}

Methods Defined Outside the Class

For longer methods, many programmers declare the method inside the class and then write its body outside. You connect the two with the scope resolution operator (::), which reads as "belongs to".

An outside method

#include <iostream>
#include <string>
using namespace std;

class BankAccount {
  public:
    string owner;
    double balance;

    void deposit(double amount);   // declaration only
};

// definition outside the class
void BankAccount::deposit(double amount) {
  balance += amount;
}

int main() {
  BankAccount acc;
  acc.owner = "Priya";
  acc.balance = 100.0;
  acc.deposit(50.0);
  cout << acc.owner << " balance: " << acc.balance;
  return 0;
}
  • Inside methods keep short logic close to the data it uses.
  • Outside methods keep the class definition tidy and easy to scan.
  • BankAccount::deposit means the deposit method that belongs to BankAccount.
  • Both styles behave exactly the same when the method runs.
Note: A method can accept parameters and return a value just like an ordinary function. The only difference is that it can also read and change the attributes of the object it was called on.

Methods let objects act on their own data. As your programs grow, keeping behavior inside the class alongside the data it uses makes your code easier to read and safer to change.