orochi
orochi

Reputation: 1258

Returning const in a function does not make the variable to be const?

I have the following structure:

class Test {
public:
    int k = 10;
};

class SecondTest {
private:
    Test t;
public:
    const Test& myTest() {
        return t;
    }
};

int main()
{
    SecondTest secondTest;
    Test tt = secondTest.myTest();
    tt.k = 20;
    cout << "tt.k value: " << tt.k;
}

I thought that:

const Test& myTest() {

would make the returning value to be const.

But no I can simply assign to a non const value and use is as a non const stuff:

Test tt = secondTest.myTest();

The print result will be

"tt.k value: 20"

This sounds so strange for me... am I missing some concept on this?

Upvotes: 0

Views: 110

Answers (1)

Jeffrey
Jeffrey

Reputation: 11430

Test tt = secondTest.myTest()

The function returns a reference to a const object. That object can't be modified.

But the Test tt = ... part triggers the copy constructor that makes a copy. This copy can be modified.

Had you written

Test& tt = secondTest.myTest()

the compiler would have emitted an error preventing you from getting a non-const reference to this object. And if you kept a const Test&, then you wouldn't have been able to modify it.

Upvotes: 7

Related Questions