Lesson 10 | Defining static and const member functions |
Objective | Define static and const member functions. |
A static
member function:
this
pointer.Syntax:
class MyClass { public: static void showCount(); };
Definition:
void MyClass::showCount() { std::cout << "Static function called\n"; }
Usage:
MyClass::showCount(); // No object needed
A const
member function:
const
member functions.Syntax:
class MyClass { private: int value; public: int getValue() const; // const after the parameter list };
Definition:
int MyClass::getValue() const { // value++; // ❌ Not allowed return value; }
Usage:
const MyClass obj; std::cout << obj.getValue(); // ✅ OK
consteval
and constexpr
alongside static
/const
for compile-time evaluation.auto
.class MyClass { int data = 42; public: static constexpr const char* description() { return "Utility Class"; } int getData() const { return data; } auto doubleData() const -> int { return data * 2; } };
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
.
// 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 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 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 */ }