Methods in C++
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:
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.