Methods in C++

#include <iostream>

class rect {
public:
    int width, height;
    
    // This area method is a member function of the rect class
    int area() {
        return width * height;
    }
    
    // Methods can be defined inside or outside the class
    int perim();
};

// Method defined outside the class
int rect::perim() {
    return 2*width + 2*height;
}

int main() {
    rect r = {10, 5};

    // Here we call the 2 methods defined for our struct
    std::cout << "area: " << r.area() << std::endl;
    std::cout << "perim: " << r.perim() << std::endl;

    // In C++, we use pointers to achieve similar behavior to Go's automatic 
    // conversion between values and pointers for method calls
    rect* rp = &r;
    std::cout << "area: " << rp->area() << std::endl;
    std::cout << "perim: " << rp->perim() << std::endl;
}

C++ supports methods defined on classes, which are similar to structs in this context.

The area method is defined inside the class, while the perim method is declared inside the class and defined outside. Both approaches are common in C++.

In C++, methods are by default non-pointer receivers. To modify the object, you either need to declare the method with a reference parameter or use a pointer to the object.

C++ doesn’t automatically handle conversion between values and pointers for method calls like Go does. Instead, we use the arrow operator (->) to call methods on pointers to objects.

To compile and run this program:

$ g++ methods.cpp -o methods
$ ./methods
area:  50
perim: 30
area:  50
perim: 30

In C++, the concept of methods is closely tied to object-oriented programming and classes. While Go’s approach to methods can work with any user-defined type, C++ methods are always associated with classes or structs.

Next, we’ll look at C++’s mechanism for defining interfaces between objects: abstract classes and pure virtual functions.