ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Object Oriented Programming
    CC-211
    Progress0 / 24 topics
    Topics
    1. Object-Oriented Design: History and Advantages2. Object-Oriented Programming: Terminology and Features3. Classes and Objects4. Data Encapsulation5. Constructors and Destructors6. Access Modifiers7. Const vs Non-Const Functions8. Static Data Members and Functions9. Function Overloading10. Operator Overloading11. Identification of Classes and Their Relationships12. Composition13. Aggregation14. Inheritance15. Multiple Inheritances16. Polymorphism17. Abstract Classes18. Interfaces19. Generic Programming Concepts20. Function Templates21. Class Templates22. Standard Template Library23. Object Streams: Data and Object Serialization24. Exception Handling
    CC-211›Const vs Non-Const Functions
    Object Oriented ProgrammingTopic 7 of 24

    Const vs Non-Const Functions

    6 minread
    1,062words
    Intermediatelevel

    Const vs Non-Const Functions in C++

    In C++, functions can be categorized as const or non-const depending on whether they are allowed to modify the object on which they are called. The concept of const in C++ is crucial for ensuring that certain member functions or methods do not change the state of an object, thus providing safety and clarity in the code.

    Non-Const Member Functions

    A non-const member function is a regular member function that can modify the state of the object it belongs to. This means it can alter the values of the member variables of the class.

    Key Characteristics of Non-Const Functions:

    1. Can Modify Object: Non-const functions can modify the object's data members (variables).
    2. No Restrictions on Object Access: These functions can access both mutable (non-const) and constant data members of the class.
    3. Can Be Used on Non-Const Objects: Non-const member functions can be called on both const and non-const objects. However, calling a non-const member function on a const object will result in a compile-time error because it would potentially modify the object.

    Example of Non-Const Function:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string brand;
        int year;
    
    public:
        Car(string b, int y) : brand(b), year(y) {}
    
        // Non-const member function that modifies the object
        void setBrand(string b) {
            brand = b;  // Modifies the object's state
        }
    
        void displayDetails() const {
            cout << "Brand: " << brand << ", Year: " << year << endl;
        }
    };
    
    int main() {
        Car car1("Toyota", 2020);
        car1.setBrand("Honda");  // Calling non-const function
        car1.displayDetails();
        
        return 0;
    }
    

    Explanation:

    • The setBrand() function is a non-const member function that modifies the brand of the Car object.
    • It can be called on a non-const object (car1), allowing the object’s state to be modified.

    Const Member Functions

    A const member function is a member function that guarantees not to modify the state of the object. This means that within a const member function, you cannot alter the values of the member variables. It is useful when you want to ensure that the function does not change the object, maintaining the integrity of the object’s state.

    Key Characteristics of Const Functions:

    1. Cannot Modify Object: A const function cannot modify any member variables of the object.
    2. Only Accesses Immutable Data: It can only access const data members or call other const member functions. It cannot change any non-const data members.
    3. Can Be Used on Const Objects: Const member functions can be called on both const and non-const objects. They are often used when we want to guarantee that an operation doesn't modify the object.
    4. Indicates Intent: It explicitly indicates that the function does not modify the object, which improves code readability and helps prevent accidental modifications.

    Syntax for Const Member Function:

    returnType functionName() const;
    

    Example of Const Function:

    #include <iostream>
    using namespace std;
    
    class Car {
    private:
        string brand;
        int year;
    
    public:
        Car(string b, int y) : brand(b), year(y) {}
    
        // Const member function that cannot modify the object
        void displayDetails() const {
            cout << "Brand: " << brand << ", Year: " << year << endl;
        }
    
        // Const function that can access only const members
        string getBrand() const {
            return brand;  // Can read but not modify brand
        }
    
        // Non-const function that modifies the object
        void setYear(int y) {
            year = y;  // Modifies the year
        }
    };
    
    int main() {
        const Car car1("Toyota", 2020);
        car1.displayDetails();  // Calling const function
    
        // car1.setYear(2021);  // Error: Cannot call non-const function on a const object
        cout << "Brand: " << car1.getBrand() << endl;
        
        return 0;
    }
    

    Explanation:

    • displayDetails() and getBrand() are const member functions, meaning they do not modify the object’s state.
    • car1 is a const object, so it can only call const functions.
    • Attempting to call setYear() on a const object results in a compilation error because setYear() is a non-const function that modifies the object.

    Const and Non-Const Member Functions: Practical Differences

    1. Access to Non-Const Members:

      • Non-const functions can modify both const and non-const members of the class.
      • Const functions can only access const members and cannot modify them.
    2. Called on Const Objects:

      • A non-const function cannot be called on a const object, because it could potentially modify the object.
      • A const function can be called on both const and non-const objects, because it guarantees not to modify the object.
    3. Const-Correctness:

      • Using const functions helps enforce const-correctness, making the code safer and more predictable by preventing accidental modification of the object.
    4. Compiler Enforcement:

      • The compiler will enforce the const-correctness, ensuring that const functions are not used inappropriately and non-const functions do not modify objects that are declared const.

    Const vs Non-Const: Use Cases

    1. Const Functions: These are useful when you want to ensure that a function does not modify the state of the object. For example:

      • Accessor methods (getter functions) that only return values without changing the object.
      • Functions that provide read-only operations on the object.
    2. Non-Const Functions: These are needed when the function needs to modify the object's state. For example:

      • Setter methods (to modify the state of the object).
      • Functions that change the internal properties or state of an object.

    Summary Table: Const vs Non-Const Member Functions

    Aspect Const Function Non-Const Function
    Modification of Object Cannot modify the object Can modify the object
    Allowed on const objects Yes, can be called on const objects No, cannot be called on const objects
    Access to Members Can only access const members Can access both const and non-const members
    Usage To guarantee the object’s state is not modified When the object’s state needs to be changed
    Syntax returnType func() const; returnType func();

    Conclusion

    In C++, const and non-const member functions provide mechanisms for controlling whether an object can be modified. Const member functions are important for ensuring that certain operations are safe and do not alter the object, while non-const functions are used when modification of the object’s state is necessary. By using const functions appropriately, we ensure const-correctness, which leads to more robust and reliable code.

    Previous topic 6
    Access Modifiers
    Next topic 8
    Static Data Members and Functions

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time6 min
      Word count1,062
      Code examples0
      DifficultyIntermediate