Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between a const and non-const function in C++

Tags:

c++

I have been reading a C++ book and found these two functions:

    int &Array::operator []( int subscript ) // first
        {
            //code

            return ptr[ subscript ]; 
         }

 int Array::operator[]( int subscript ) const //second
{
    //code

    return ptr[ subscript ]; // value return
}

The idea is to create an Array object and access some private members, for example:

Array myArray;
cout << myArray[ 2 ];

But I don't get the difference between those functions, basically because every time I type something like "cout << myArray[ 2 ]" the first function is called. So , when is the second function called? Does the second function work?

like image 219
Beats2019 Avatar asked Jul 04 '19 23:07

Beats2019


People also ask

What is difference between constant and non constant in C?

It is a fixed variable that cannot be changed after defining the variable in a program. The value of a variable can change depending on the conditions. In constants, the value cannot be changed. Typically, it uses int, float, char, string, double, etc.

What is difference between constant and non constant?

Constant Functions means that they will remain same throughout the execution of the program. Non-constant variable are those whose value can be changed at any point during the execution of the program. Therefore, Non constant variables can't be used because they change the behaviour of the function.

What is difference between constant function and non constant function in C++?

Const member functions in C++ It is recommended to use const keyword so that accidental changes to object are avoided. A const member function can be called by any type of object. Non-const functions can be called by non-const objects only.

Can a non-const function call a const function?

const member functions may be invoked for const and non-const objects. non-const member functions can only be invoked for non-const objects. If a non-const member function is invoked on a const object, it is a compiler error.


1 Answers

Since you're declaring a mutable Array instance, the first function is used.

You need a const instance in order for the second one to be used:

const Array myArray;

// As this is const, only the second function can work
cout << myArray[2];

If you read the function signatures carefully, the second one has const at the end which means it applies to const instances. Normally if no non-const version is defined, this is the one that will run, but as you've gone out of your way to make the other version, that's the one that's called.

The first function allows mutation because it returns a reference instead of a copy:

myArray[2] = 5;

Where that actually changes the array. The const version does not permit this, you get a temporary value instead.

like image 88
tadman Avatar answered Sep 28 '22 06:09

tadman