Tech

Class Methods & Separating Interface From Implementation–C++ Notes (C Plus Plus Notes)

Class Methods

Methods, or member functions, are functions that belong to the class.

  • There are two ways to define functions that belong to a class, or member functions, or methods.
    • Inside the class definition
    • Outside the class definition (including from a different file like a source file)

To define a member function outside the class definition, you have to declare it inside the class (with a function prototype), and then define it outside of the class. This is done by specifying the name of the class, followed by the scope resolution operator ( :: ), followed by the name of the function.

Separating Interface from Implementation

*Note: It’s better software engineering to define member functions outside the class definition, so that their implementation details can be hidden from the client code (e.g. function ‘main’). This practice ENSURES that you do not write client code that depends on the class’s implementation details. (If the client code DOES know how a class is implemented, the client-code programmer might write client code based on the class’s implementation details. But, ideally, if that implementation changes, the class’s clients should NOT have to change. Hiding the class’s implementation details makes it easier to change the class’s implementation while minimizing, and hopefully eliminating, changes to client code. This is know as separating interface from implementation.

*All the above relates directly to how you should organize your code into header files and source files. The rule of thumb is this: Header files should contain declarations, and source files should contain definitions.