TExcelTAD
Home › C++ › C++ Class Methods

C++ Class Methods

Methods (member functions) are functions that belong to a class. They are called on an object with the dot operator and can freely read and modify that object's attributes.

Defining methods inside and outside the class

You can write a method's body directly inside the class, or only declare it there and define it outside using the scope resolution operator ::. Larger projects use the second style: the class goes in a header, the method bodies in a .cpp file.

cpp · try it yourself
#include <iostream>
using namespace std;

class Rectangle {
public:
    double width = 0;
    double height = 0;

    double area() const {               // defined inside the class
        return width * height;
    }
    double perimeter() const;           // only declared here
    void scale(double factor);
};

double Rectangle::perimeter() const {   // defined outside
    return 2 * (width + height);
}

void Rectangle::scale(double factor) {
    width *= factor;
    height *= factor;
}

int main() {
    Rectangle r;
    r.width = 3;
    r.height = 2;
    cout << "area " << r.area() << ", perimeter " << r.perimeter() << "\n";
    r.scale(2);
    cout << "area " << r.area() << ", perimeter " << r.perimeter() << "\n";
}
area 6, perimeter 10
area 24, perimeter 20

const methods

A method marked const (after the parameter list) promises not to modify the object. The compiler enforces the promise, and only const methods can be called on const objects or through const references:

cpp
class Counter {
public:
    int value = 0;
    int get() const { return value; }       // OK: only reads
    void inc() { value++; }
    void bad() const { value++; }           // ERROR: modifying in a const method
};

void show(const Counter& c) {
    cout << c.get();    // OK
    c.inc();            // ERROR: inc() is not const
}

Tip: Mark every method that does not change the object as const. It documents intent and makes your class usable with const references.

The this pointer

Inside a method, this is a pointer to the object the method was called on. You rarely need it explicitly, but it is useful when a parameter has the same name as a member, or when a method returns the object itself to allow method chaining:

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

class Message {
public:
    string text;

    Message& append(const string& text) {
        this->text += text;      // this->text is the member, text is the parameter
        return *this;            // return the object itself
    }
    Message& exclaim() {
        text += "!";
        return *this;
    }
};

int main() {
    Message m;
    m.append("Hello").append(", ").append("chaining").exclaim();
    cout << m.text << "\n";
}
Hello, chaining!

Methods with parameters and return values

Methods can take parameters and return values like any function — including other objects of the same class:

cpp · try it yourself
#include <iostream>
#include <cmath>
using namespace std;

class Point {
public:
    double x = 0, y = 0;

    double distanceTo(const Point& other) const {
        return hypot(x - other.x, y - other.y);
    }
    Point midpoint(const Point& other) const {
        return Point{(x + other.x) / 2, (y + other.y) / 2};
    }
    void print() const {
        cout << "(" << x << ", " << y << ")";
    }
};

int main() {
    Point a{0, 0};
    Point b{6, 8};
    cout << "distance: " << a.distanceTo(b) << "\n";
    cout << "midpoint: ";
    a.midpoint(b).print();
    cout << "\n";
}
distance: 10
midpoint: (3, 4)

Static members

A static member belongs to the class itself, not to any single object. All objects share it, and you can access it with ClassName::member:

cpp · try it yourself
#include <iostream>
#include <string>
using namespace std;

class Ticket {
public:
    inline static int issued = 0;      // shared by all tickets (C++17 inline static)
    int number;
    string event;

    static Ticket create(const string& ev) {
        issued++;
        return Ticket{issued, ev};
    }
};

int main() {
    Ticket t1 = Ticket::create("Concert");
    Ticket t2 = Ticket::create("Concert");
    Ticket t3 = Ticket::create("Museum");
    cout << t1.event << " #" << t1.number << "\n";
    cout << t3.event << " #" << t3.number << "\n";
    cout << "Issued so far: " << Ticket::issued << "\n";
}
Concert #1
Museum #3
Issued so far: 3

A static method has no this pointer, so it can only use static members directly.

Test yourself

How do you define the method area of class Box outside the class?

  1. double area::Box() {...}
  2. double Box.area() {...}
  3. double Box::area() {...}
  4. double Box->area() {...}

What does const after a method's parameter list mean?

  1. It returns a constant
  2. It cannot modify the object
  3. It can only be called once
  4. It is a static method

What is this inside a member function?

  1. A copy of the object
  2. A pointer to the object the method was called on
  3. The class name
  4. A reference to the first member