Page Content

Tutorials

Const Member Functions In C++: What They Are & Why It Matter

Learn about the Const Objects and Const Member Functions In C++.

Const Member Functions and Objects

The const keyword in C++ is a strong tool for ensuring immutability and enhancing the safety and readability of programs. It can be used on both class member functions and objects.

Const Objects

Declaring an object as const means that after it has been initialized, its value cannot be altered. A const object needs to be initialized at the moment of definition since it cannot be allocated to anything.

  • Initialization: Upon creation, the value of a const object is set. It is possible for constructors to write to class-type const objects while they are being constructed since the “constness” of these objects is applied after the constructor has finished initialising the object.
  • Operations: Only actions that don’t alter its state can be performed on a const object. This basically indicates that it can only invoke functions that are const members. Calling a const object’s non-const member function triggers a compiler error.

Const Member Functions In C++

A class method that ensures it won’t alter any of the data members of its class is called a const member function. The compiler and the programmer are both promised this.

  • Declaration and Definition: Put the const keyword before the function body but after the argument list to declare a member function as const. Functions declared inside the class and defined outside must have the const keyword in both declaration and definition.
  • this Pointer: The implication In a const member function, this pointer to the object called on is handled as const. This prevents the function from changing object non-mutable data.
  • Calling Other Members: Only other const member functions of the same object can be called by a const member function.
  • Purpose: Functions that solely read data from an object, such as accessors or getter methods, are excellent candidates to be declared const.

Relationship Between Const Objects and Const Member Functions

The fundamental tenet is that only const member functions can communicate with const objects. The compiler imposes this constraint in order to uphold the promise of immutability of const objects. Marking a function as const permits it to be called on const objects if it is intended to not change the state of an object.

Benefits of Using

  • Compiler-Enforced Safety: Const aids the compiler in detecting unintentional object modifications during compilation.
  • Clarity and Readability: It makes it very evident to other programmers that an object’s value is fixed or that a function is not meant to alter the object’s state.
  • Enabling const Objects: Const objects can be used in your program by designating functions that don’t change data as const.
  • Optimization: Knowing that a function or object won’t change allows compilers to optimise more effectively.
  • Overloading: Depending on their const qualification, member functions can be overloaded, giving const versus non-const objects distinct behaviour.

The Key word

Even if the object (or member function that uses it) is const, changing a data member is rare. In some cases, the changeable keyword can declare the data member. A const member function has the ability to alter the value of a mutable member, which is never const. This is usually applied to internal state, such as a cache, that does not logically change the object’s public logical state.

Code Example

#include <iostream>
#include <string>
class Book {
private:
    std::string title;
    int pages;
public:
    Book(const std::string& t, int p) : title(t), pages(p) {
        std::cout << "Book '" << title << "' created." << std::endl;
    }
    void displayInfo() const {
        std::cout << "Title: " << title << ", Pages: " << pages << std::endl;
    }
    void updatePages(int newPages) {
        pages = newPages;
        std::cout << "Pages updated to: " << pages << std::endl;
    }
    void nonConstMethod() {
        std::cout << "This is a non-const method." << std::endl;
    }
};
// 
int main() {
    Book myBook("Book Title", 100);
    myBook.displayInfo();
    myBook.updatePages(150);
    myBook.displayInfo(); // Display info again to see updated pages
    myBook.nonConstMethod();
    return 0;
}

Output

Book 'Book Title' created.
Title: Book Title, Pages: 100
Pages updated to: 150
Title: Book Title, Pages: 150
This is a non-const method.

You can also read Static Data Members And Static Member Functions In C++

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index