C++ Class Construct  «Prev  Next»
Lesson 10 Defining static and const member functions
ObjectiveDefine static and const member functions.

Defining static and const Member Functions in C++

Define Static Member Functions
C++ allows static and const member functions.

Defining static and const member functions

Use const whenever possible, including when modifying member functions. The use of const allows the compiler to test additional features of your code. It is part of the static type-safety of the C++ language. It is also useful documentation and potentially an aid in optimization. Using the class name with the scope resolution operator instead of the variable name with the dot operator makes it clear that the variable being referenced is static.
Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called. To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. The const keyword is required in both the declaration and the definition. A constant member function cannot modify any data members or call any member functions that aren't constant.

// constant_member_function.cpp
class Date{
public:
  Date( int mn, int dy, int yr );
  int getMonth() const;     // A read-only function
  void setMonth( int mn );   // A write function; can't be const
private:
   int month;
};

int Date::getMonth() const
{
   return month;        // Doesn't modify anything
}
void Date::setMonth( int mn )
{
   month = mn;          // Modifies data member
}
int main()
{
   Date MyDate( 7, 4, 1998 );
   const Date BirthDate( 1, 18, 1953 );
   MyDate.setMonth( 4 );    // Okay
   BirthDate.getMonth();    // Okay
   BirthDate.setMonth( 4 ); // C2662 Error
}


static member function syntax

A static member function has the modifier static precede the return type inside the class declaration. A definition outside the class must not have the static modifier.

class foo {
.....
   static int  foo_fcn();  //static goes first
.....
};

int foo::foo_fcn()//no static keyword here
{  /* definition */ }

const member function syntax

A const member function has the modifier const follow the argument list inside the class declaration. A definition outside the class must have the const modifier.
class foo {
.....
   int  foo_fcn() const;
.....
};

int foo::foo_fcn() const   //const keyword needed
{  /* definition */ }

SEMrush Software