Member Functions

Member functions implement the behavior of a class. Member functions can be defined within the class definition or separately. You can use the inline function specifier and either the static or virtual (but not both) specifier. (See Chapter 2 for more about function specifiers.) Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier.

A nonstatic member function can have const, volatile, or both function qualifiers. Qualifiers appear after the function parameters and before the exception specification. Function qualifiers are discussed in the next section, Section 6.3.2.

Example 6-8 shows various member function declarations and definitions.

Example 6-8. Declaring and defining member functions
#include <cmath> #include <iostream> #include <istream> #include <ostream> class point { public: typedef double value_type; // Constructors are special member functions. explicit point(value_type x = 0.0, value_type y = 0.0); value_type x( ) const { return x_; } value_type y( ) const { return y_; } void x(value_type x) { x_ = x; } void y(value_type y) { y_ = y; } value_type distance( ) const; bool operator==(const point& pt) const; inline static point origin( ); private: value_type x_, y_; }; point::point(value_type x, value_type y) : x_(x), y_(y) {} point::value_type point::distance( ) const { return std::sqrt(x() * x() + y( ) * y( )); } bool point::operator==(const point& pt) const { return x() == pt.x() ...

Get C++ In a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.