ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCC-211Const Vs Non Const Fun…
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CC-211

    Object Oriented Programming

    Progress0 / 24 done
    Topics24
    1History and Advantages
    2Terminology and Features3Classes and Objects4Data Encapsulation5Constructors and Destructors6Access Modifiers7Const vs Non-Const Functions8Static Data Members and Functions9Function Overloading10Operator Overloading11Identification of Classes and Their Relationships12Composition13Aggregation14Inheritance15Multiple Inheritances16Polymorphism17Abstract Classes18Interfaces19Generic Programming Concepts20Function Templates21Class Templates22Standard Template Library
    23Data and Object Serialization24Exception Handling
    6 min read
    Topic 7 of 24
    Topic Study Note Illustration
    07

    Const vs Non-Const Functions

    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...

    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 view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    6mremaining
    1.1kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Object Oriented Programming