Search⌘ K

Methods

Explore the different types of methods in C++ classes and structs, including normal, static, const, and constexpr methods. Understand how to define them inside and outside classes, use the this pointer to access attributes, and learn the distinctions between const and constexpr for safety and performance optimization.

As we discussed earlier, methods are the functions associated with a class or struct. Normal methods can only be called through a class instance. However, static methods can be called without an instance as well.

Defining methods #

A class method has to be declared inside the class, but can be defined outside using the scope resolution operator, ::.

struct Account{
  double getBalance() const;
  void withdraw(double amt);
  void deposit(double amt) { balance += amt; }
private:
  double balance;
};

double Account::getBalance() const { return balance; }
inline void Account::withdraw(double amt){ balance -= amt; }

If it is defined inside the class, the compiler automatically considers it an inline function.

this pointer

...