nihal dixit
nihal dixit

Reputation: 53

Can const value be changed using initialiser list?

I have initialized the const reference z and tried to reinitialize it using initializer list and the output I am getting is the changed value. No errors no warnings.

#include <iostream>
using namespace std;
class Point {
    private:
    const int &z=9;

    public:
    Point (int &c):z(c){}

    int get_setz(){
        return z;
    }

};

int main()
{
    int m=3;
    Point p(m);
    cout << p.get_setz();
    return 0;
}

Output :
3

Upvotes: 0

Views: 52

Answers (1)

I have initialized the const reference z and tried to reinitialize

You tried, but you didn't. When a constructor member initialization list is used to initialize a member, any default member initializer is ignored. z never referred to a temporary with the value 9. So the rules of C++ are still very much in play, you may not reseat a reference, and there was never even an attempt to do so.

And had you not initialized z with c, you'd have a dangling reference and code with undefined behavior on your hands. Because that 9 is not an object, it's a literal. References can only bind to objects, and so you'd have bound it to a temporary that would have gone out of scope once the initialization of your object was complete.

Upvotes: 5

Related Questions