What are const member functions?

0241

Const member functions in C++ are member functions of a class that are declared with the const keyword at the end of their declaration. The primary purpose of const member functions is to indicate that they do not modify the state of the object on which they are called. This provides a guarantee to the caller that the object's data members will remain unchanged.

Key Features of Const Member Functions:

  1. Declaration: A const member function is declared by appending const to the function signature.

    class MyClass {
    public:
        void display() const; // Const member function
    };
  2. No Modification: Inside a const member function, you cannot modify any non-static member variables of the class. Attempting to do so will result in a compilation error.

    class MyClass {
    private:
        int value;
    public:
        void setValue(int v) {
            value = v; // This can modify the member variable
        }
        
        void display() const {
            // value = 10; // This will cause a compilation error
            std::cout << value;
        }
    };
  3. Usage with Const Objects: Const member functions can be called on const instances of the class. This allows you to use const objects while ensuring that their state remains unchanged.

    void printValue(const MyClass& obj) {
        obj.display(); // Allowed because display() is a const member function
    }
  4. Overloading: You can overload member functions based on constness. For example, you can have a const and a non-const version of the same function.

    class MyClass {
    public:
        int getValue() const {
            return 42; // Const version
        }
        
        int getValue() {
            return 24; // Non-const version
        }
    };

Example:

Here’s a complete example demonstrating const member functions:

#include <iostream>

class MyClass {
private:
    int value;
public:
    MyClass(int v) : value(v) {}

    void setValue(int v) {
        value = v; // Modifies the member variable
    }

    void display() const {
        std::cout << "Value: " << value << std::endl; // Cannot modify value
    }
};

int main() {
    MyClass obj(10);
    obj.display(); // Output: Value: 10

    obj.setValue(20);
    obj.display(); // Output: Value: 20

    const MyClass constObj(30);
    constObj.display(); // Output: Value: 30
    // constObj.setValue(40); // This would cause a compilation error

    return 0;
}

In this example, display() is a const member function that guarantees it will not modify the value member variable.

0 Comments

no data
Be the first to share your comment!